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 // Comparisons that require checking two conditions.
414 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
415 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
416 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
417 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
418 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
419 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
420 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
421 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
422 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
423 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
424 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
425 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
427 if (Subtarget.has64BitSupport()) {
428 // They also have instructions for converting between i64 and fp.
429 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
430 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
431 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
432 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
433 // This is just the low 32 bits of a (signed) fp->i64 conversion.
434 // We cannot do this with Promote because i64 is not a legal type.
435 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
437 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
438 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
440 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
441 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
444 // With the instructions enabled under FPCVT, we can do everything.
445 if (Subtarget.hasFPCVT()) {
446 if (Subtarget.has64BitSupport()) {
447 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
448 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
449 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
450 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
453 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
454 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
455 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
456 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
459 if (Subtarget.use64BitRegs()) {
460 // 64-bit PowerPC implementations can support i64 types directly
461 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
462 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
463 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
464 // 64-bit PowerPC wants to expand i128 shifts itself.
465 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
466 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
467 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
469 // 32-bit PowerPC wants to expand i64 shifts itself.
470 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
471 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
472 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
475 if (Subtarget.hasAltivec()) {
476 // First set operation action for all vector types to expand. Then we
477 // will selectively turn on ones that can be effectively codegen'd.
478 for (MVT VT : MVT::vector_valuetypes()) {
479 // add/sub are legal for all supported vector VT's.
480 setOperationAction(ISD::ADD, VT, Legal);
481 setOperationAction(ISD::SUB, VT, Legal);
483 // Vector instructions introduced in P8
484 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
485 setOperationAction(ISD::CTPOP, VT, Legal);
486 setOperationAction(ISD::CTLZ, VT, Legal);
489 setOperationAction(ISD::CTPOP, VT, Expand);
490 setOperationAction(ISD::CTLZ, VT, Expand);
493 // Vector instructions introduced in P9
494 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
495 setOperationAction(ISD::CTTZ, VT, Legal);
497 setOperationAction(ISD::CTTZ, VT, Expand);
499 // We promote all shuffles to v16i8.
500 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
501 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
503 // We promote all non-typed operations to v4i32.
504 setOperationAction(ISD::AND , VT, Promote);
505 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
506 setOperationAction(ISD::OR , VT, Promote);
507 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
508 setOperationAction(ISD::XOR , VT, Promote);
509 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
510 setOperationAction(ISD::LOAD , VT, Promote);
511 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
512 setOperationAction(ISD::SELECT, VT, Promote);
513 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
514 setOperationAction(ISD::SELECT_CC, VT, Promote);
515 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
516 setOperationAction(ISD::STORE, VT, Promote);
517 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
519 // No other operations are legal.
520 setOperationAction(ISD::MUL , VT, Expand);
521 setOperationAction(ISD::SDIV, VT, Expand);
522 setOperationAction(ISD::SREM, VT, Expand);
523 setOperationAction(ISD::UDIV, VT, Expand);
524 setOperationAction(ISD::UREM, VT, Expand);
525 setOperationAction(ISD::FDIV, VT, Expand);
526 setOperationAction(ISD::FREM, VT, Expand);
527 setOperationAction(ISD::FNEG, VT, Expand);
528 setOperationAction(ISD::FSQRT, VT, Expand);
529 setOperationAction(ISD::FLOG, VT, Expand);
530 setOperationAction(ISD::FLOG10, VT, Expand);
531 setOperationAction(ISD::FLOG2, VT, Expand);
532 setOperationAction(ISD::FEXP, VT, Expand);
533 setOperationAction(ISD::FEXP2, VT, Expand);
534 setOperationAction(ISD::FSIN, VT, Expand);
535 setOperationAction(ISD::FCOS, VT, Expand);
536 setOperationAction(ISD::FABS, VT, Expand);
537 setOperationAction(ISD::FPOWI, VT, Expand);
538 setOperationAction(ISD::FFLOOR, VT, Expand);
539 setOperationAction(ISD::FCEIL, VT, Expand);
540 setOperationAction(ISD::FTRUNC, VT, Expand);
541 setOperationAction(ISD::FRINT, VT, Expand);
542 setOperationAction(ISD::FNEARBYINT, VT, Expand);
543 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
544 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
545 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
546 setOperationAction(ISD::MULHU, VT, Expand);
547 setOperationAction(ISD::MULHS, VT, Expand);
548 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
549 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
550 setOperationAction(ISD::UDIVREM, VT, Expand);
551 setOperationAction(ISD::SDIVREM, VT, Expand);
552 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
553 setOperationAction(ISD::FPOW, VT, Expand);
554 setOperationAction(ISD::BSWAP, VT, Expand);
555 setOperationAction(ISD::VSELECT, VT, Expand);
556 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
557 setOperationAction(ISD::ROTL, VT, Expand);
558 setOperationAction(ISD::ROTR, VT, Expand);
560 for (MVT InnerVT : MVT::vector_valuetypes()) {
561 setTruncStoreAction(VT, InnerVT, Expand);
562 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
563 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
564 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
568 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
569 // with merges, splats, etc.
570 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
572 setOperationAction(ISD::AND , MVT::v4i32, Legal);
573 setOperationAction(ISD::OR , MVT::v4i32, Legal);
574 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
575 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
576 setOperationAction(ISD::SELECT, MVT::v4i32,
577 Subtarget.useCRBits() ? Legal : Expand);
578 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
579 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
580 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
581 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
582 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
583 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
584 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
585 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
586 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
588 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
589 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
590 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
591 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
593 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
594 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
596 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
597 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
598 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
601 if (Subtarget.hasP8Altivec())
602 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
604 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
606 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
607 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
609 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
610 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
612 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
613 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
614 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
615 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
617 // Altivec does not contain unordered floating-point compare instructions
618 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
619 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
620 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
621 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
623 if (Subtarget.hasVSX()) {
624 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
625 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
626 if (Subtarget.hasP8Vector()) {
627 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
628 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
630 if (Subtarget.hasDirectMove() && isPPC64) {
631 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
632 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
633 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
634 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
635 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
636 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
637 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
638 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
640 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
642 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
643 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
644 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
645 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
646 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
648 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
650 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
651 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
653 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
654 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
656 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
657 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
658 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
659 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
660 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
662 // Share the Altivec comparison restrictions.
663 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
664 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
665 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
666 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
668 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
669 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
671 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
673 if (Subtarget.hasP8Vector())
674 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
676 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
678 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
679 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
680 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
682 if (Subtarget.hasP8Altivec()) {
683 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
684 setOperationAction(ISD::SRA, MVT::v2i64, Legal);
685 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
687 setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
690 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
691 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
692 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
694 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
696 // VSX v2i64 only supports non-arithmetic operations.
697 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
698 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
701 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
702 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
703 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
704 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
706 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
708 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
709 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
710 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
711 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
713 // Vector operation legalization checks the result type of
714 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
715 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
716 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
717 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
718 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
720 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
721 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
722 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
723 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
725 if (Subtarget.hasDirectMove())
726 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
727 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
729 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
732 if (Subtarget.hasP8Altivec()) {
733 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
734 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
737 if (Subtarget.hasP9Vector()) {
738 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
739 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
743 if (Subtarget.hasQPX()) {
744 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
745 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
746 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
747 setOperationAction(ISD::FREM, MVT::v4f64, Expand);
749 setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
750 setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
752 setOperationAction(ISD::LOAD , MVT::v4f64, Custom);
753 setOperationAction(ISD::STORE , MVT::v4f64, Custom);
755 setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
756 setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
758 if (!Subtarget.useCRBits())
759 setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
760 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
762 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
763 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
764 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
765 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
766 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
767 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
768 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
770 setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
771 setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
773 setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
774 setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
775 setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
777 setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
778 setOperationAction(ISD::FABS , MVT::v4f64, Legal);
779 setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
780 setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
781 setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
782 setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
783 setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
784 setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
785 setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
786 setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
787 setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
789 setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
790 setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
792 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
793 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
795 addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
797 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
798 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
799 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
800 setOperationAction(ISD::FREM, MVT::v4f32, Expand);
802 setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
803 setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
805 setOperationAction(ISD::LOAD , MVT::v4f32, Custom);
806 setOperationAction(ISD::STORE , MVT::v4f32, Custom);
808 if (!Subtarget.useCRBits())
809 setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
810 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
812 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
813 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
814 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
815 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
816 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
817 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
818 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
820 setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
821 setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
823 setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
824 setOperationAction(ISD::FABS , MVT::v4f32, Legal);
825 setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
826 setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
827 setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
828 setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
829 setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
830 setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
831 setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
832 setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
833 setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
835 setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
836 setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
838 setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
839 setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
841 addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
843 setOperationAction(ISD::AND , MVT::v4i1, Legal);
844 setOperationAction(ISD::OR , MVT::v4i1, Legal);
845 setOperationAction(ISD::XOR , MVT::v4i1, Legal);
847 if (!Subtarget.useCRBits())
848 setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
849 setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
851 setOperationAction(ISD::LOAD , MVT::v4i1, Custom);
852 setOperationAction(ISD::STORE , MVT::v4i1, Custom);
854 setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
855 setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
856 setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
857 setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
858 setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
859 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
860 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
862 setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
863 setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
865 addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
867 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
868 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
869 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
870 setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
872 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
873 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
874 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
875 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
877 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
878 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
880 // These need to set FE_INEXACT, and so cannot be vectorized here.
881 setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
882 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
884 if (TM.Options.UnsafeFPMath) {
885 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
886 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
888 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
889 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
891 setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
892 setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
894 setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
895 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
899 if (Subtarget.has64BitSupport())
900 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
902 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
905 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
906 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
909 setBooleanContents(ZeroOrOneBooleanContent);
911 if (Subtarget.hasAltivec()) {
912 // Altivec instructions set fields to all zeros or all ones.
913 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
917 // These libcalls are not available in 32-bit.
918 setLibcallName(RTLIB::SHL_I128, nullptr);
919 setLibcallName(RTLIB::SRL_I128, nullptr);
920 setLibcallName(RTLIB::SRA_I128, nullptr);
923 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
925 // We have target-specific dag combine patterns for the following nodes:
926 setTargetDAGCombine(ISD::SHL);
927 setTargetDAGCombine(ISD::SRA);
928 setTargetDAGCombine(ISD::SRL);
929 setTargetDAGCombine(ISD::SINT_TO_FP);
930 setTargetDAGCombine(ISD::BUILD_VECTOR);
931 if (Subtarget.hasFPCVT())
932 setTargetDAGCombine(ISD::UINT_TO_FP);
933 setTargetDAGCombine(ISD::LOAD);
934 setTargetDAGCombine(ISD::STORE);
935 setTargetDAGCombine(ISD::BR_CC);
936 if (Subtarget.useCRBits())
937 setTargetDAGCombine(ISD::BRCOND);
938 setTargetDAGCombine(ISD::BSWAP);
939 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
940 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
941 setTargetDAGCombine(ISD::INTRINSIC_VOID);
943 setTargetDAGCombine(ISD::SIGN_EXTEND);
944 setTargetDAGCombine(ISD::ZERO_EXTEND);
945 setTargetDAGCombine(ISD::ANY_EXTEND);
947 if (Subtarget.useCRBits()) {
948 setTargetDAGCombine(ISD::TRUNCATE);
949 setTargetDAGCombine(ISD::SETCC);
950 setTargetDAGCombine(ISD::SELECT_CC);
953 // Use reciprocal estimates.
954 if (TM.Options.UnsafeFPMath) {
955 setTargetDAGCombine(ISD::FDIV);
956 setTargetDAGCombine(ISD::FSQRT);
959 // Darwin long double math library functions have $LDBL128 appended.
960 if (Subtarget.isDarwin()) {
961 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
962 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
963 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
964 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
965 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
966 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
967 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
968 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
969 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
970 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
973 // With 32 condition bits, we don't need to sink (and duplicate) compares
974 // aggressively in CodeGenPrep.
975 if (Subtarget.useCRBits()) {
976 setHasMultipleConditionRegisters();
977 setJumpIsExpensive();
980 setMinFunctionAlignment(2);
981 if (Subtarget.isDarwin())
982 setPrefFunctionAlignment(4);
984 switch (Subtarget.getDarwinDirective()) {
988 case PPC::DIR_E500mc:
998 setPrefFunctionAlignment(4);
999 setPrefLoopAlignment(4);
1003 if (Subtarget.enableMachineScheduler())
1004 setSchedulingPreference(Sched::Source);
1006 setSchedulingPreference(Sched::Hybrid);
1008 computeRegisterProperties(STI.getRegisterInfo());
1010 // The Freescale cores do better with aggressive inlining of memcpy and
1011 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1012 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1013 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1014 MaxStoresPerMemset = 32;
1015 MaxStoresPerMemsetOptSize = 16;
1016 MaxStoresPerMemcpy = 32;
1017 MaxStoresPerMemcpyOptSize = 8;
1018 MaxStoresPerMemmove = 32;
1019 MaxStoresPerMemmoveOptSize = 8;
1020 } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1021 // The A2 also benefits from (very) aggressive inlining of memcpy and
1022 // friends. The overhead of a the function call, even when warm, can be
1023 // over one hundred cycles.
1024 MaxStoresPerMemset = 128;
1025 MaxStoresPerMemcpy = 128;
1026 MaxStoresPerMemmove = 128;
1030 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1031 /// the desired ByVal argument alignment.
1032 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1033 unsigned MaxMaxAlign) {
1034 if (MaxAlign == MaxMaxAlign)
1036 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1037 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1039 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1041 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1042 unsigned EltAlign = 0;
1043 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1044 if (EltAlign > MaxAlign)
1045 MaxAlign = EltAlign;
1046 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1047 for (auto *EltTy : STy->elements()) {
1048 unsigned EltAlign = 0;
1049 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1050 if (EltAlign > MaxAlign)
1051 MaxAlign = EltAlign;
1052 if (MaxAlign == MaxMaxAlign)
1058 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1059 /// function arguments in the caller parameter area.
1060 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1061 const DataLayout &DL) const {
1062 // Darwin passes everything on 4 byte boundary.
1063 if (Subtarget.isDarwin())
1066 // 16byte and wider vectors are passed on 16byte boundary.
1067 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1068 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1069 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1070 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1074 bool PPCTargetLowering::useSoftFloat() const {
1075 return Subtarget.useSoftFloat();
1078 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1079 switch ((PPCISD::NodeType)Opcode) {
1080 case PPCISD::FIRST_NUMBER: break;
1081 case PPCISD::FSEL: return "PPCISD::FSEL";
1082 case PPCISD::FCFID: return "PPCISD::FCFID";
1083 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
1084 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
1085 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
1086 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
1087 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
1088 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
1089 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
1090 case PPCISD::FRE: return "PPCISD::FRE";
1091 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
1092 case PPCISD::STFIWX: return "PPCISD::STFIWX";
1093 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
1094 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
1095 case PPCISD::VPERM: return "PPCISD::VPERM";
1096 case PPCISD::XXSPLT: return "PPCISD::XXSPLT";
1097 case PPCISD::XXINSERT: return "PPCISD::XXINSERT";
1098 case PPCISD::VECSHL: return "PPCISD::VECSHL";
1099 case PPCISD::CMPB: return "PPCISD::CMPB";
1100 case PPCISD::Hi: return "PPCISD::Hi";
1101 case PPCISD::Lo: return "PPCISD::Lo";
1102 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
1103 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
1104 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET";
1105 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
1106 case PPCISD::SRL: return "PPCISD::SRL";
1107 case PPCISD::SRA: return "PPCISD::SRA";
1108 case PPCISD::SHL: return "PPCISD::SHL";
1109 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE";
1110 case PPCISD::CALL: return "PPCISD::CALL";
1111 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
1112 case PPCISD::MTCTR: return "PPCISD::MTCTR";
1113 case PPCISD::BCTRL: return "PPCISD::BCTRL";
1114 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
1115 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
1116 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
1117 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
1118 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1119 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
1120 case PPCISD::MFVSR: return "PPCISD::MFVSR";
1121 case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
1122 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
1123 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP";
1124 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP";
1125 case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT";
1126 case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT";
1127 case PPCISD::VCMP: return "PPCISD::VCMP";
1128 case PPCISD::VCMPo: return "PPCISD::VCMPo";
1129 case PPCISD::LBRX: return "PPCISD::LBRX";
1130 case PPCISD::STBRX: return "PPCISD::STBRX";
1131 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
1132 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
1133 case PPCISD::LXSIZX: return "PPCISD::LXSIZX";
1134 case PPCISD::STXSIX: return "PPCISD::STXSIX";
1135 case PPCISD::VEXTS: return "PPCISD::VEXTS";
1136 case PPCISD::LXVD2X: return "PPCISD::LXVD2X";
1137 case PPCISD::STXVD2X: return "PPCISD::STXVD2X";
1138 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
1139 case PPCISD::BDNZ: return "PPCISD::BDNZ";
1140 case PPCISD::BDZ: return "PPCISD::BDZ";
1141 case PPCISD::MFFS: return "PPCISD::MFFS";
1142 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
1143 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
1144 case PPCISD::CR6SET: return "PPCISD::CR6SET";
1145 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
1146 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
1147 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT";
1148 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1149 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
1150 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
1151 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
1152 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1153 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1154 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1155 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1156 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1157 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1158 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1159 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1160 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1161 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1162 case PPCISD::SC: return "PPCISD::SC";
1163 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB";
1164 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE";
1165 case PPCISD::RFEBB: return "PPCISD::RFEBB";
1166 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD";
1167 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN";
1168 case PPCISD::QVFPERM: return "PPCISD::QVFPERM";
1169 case PPCISD::QVGPCI: return "PPCISD::QVGPCI";
1170 case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI";
1171 case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI";
1172 case PPCISD::QBFLT: return "PPCISD::QBFLT";
1173 case PPCISD::QVLFSb: return "PPCISD::QVLFSb";
1178 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1181 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1183 if (Subtarget.hasQPX())
1184 return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1186 return VT.changeVectorElementTypeToInteger();
1189 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1190 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1194 //===----------------------------------------------------------------------===//
1195 // Node matching predicates, for use by the tblgen matching code.
1196 //===----------------------------------------------------------------------===//
1198 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1199 static bool isFloatingPointZero(SDValue Op) {
1200 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1201 return CFP->getValueAPF().isZero();
1202 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1203 // Maybe this has already been legalized into the constant pool?
1204 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1205 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1206 return CFP->getValueAPF().isZero();
1211 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1212 /// true if Op is undef or if it matches the specified value.
1213 static bool isConstantOrUndef(int Op, int Val) {
1214 return Op < 0 || Op == Val;
1217 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1218 /// VPKUHUM instruction.
1219 /// The ShuffleKind distinguishes between big-endian operations with
1220 /// two different inputs (0), either-endian operations with two identical
1221 /// inputs (1), and little-endian operations with two different inputs (2).
1222 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1223 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1224 SelectionDAG &DAG) {
1225 bool IsLE = DAG.getDataLayout().isLittleEndian();
1226 if (ShuffleKind == 0) {
1229 for (unsigned i = 0; i != 16; ++i)
1230 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1232 } else if (ShuffleKind == 2) {
1235 for (unsigned i = 0; i != 16; ++i)
1236 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1238 } else if (ShuffleKind == 1) {
1239 unsigned j = IsLE ? 0 : 1;
1240 for (unsigned i = 0; i != 8; ++i)
1241 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1242 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1248 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1249 /// VPKUWUM instruction.
1250 /// The ShuffleKind distinguishes between big-endian operations with
1251 /// two different inputs (0), either-endian operations with two identical
1252 /// inputs (1), and little-endian operations with two different inputs (2).
1253 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1254 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1255 SelectionDAG &DAG) {
1256 bool IsLE = DAG.getDataLayout().isLittleEndian();
1257 if (ShuffleKind == 0) {
1260 for (unsigned i = 0; i != 16; i += 2)
1261 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1262 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1264 } else if (ShuffleKind == 2) {
1267 for (unsigned i = 0; i != 16; i += 2)
1268 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1269 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1271 } else if (ShuffleKind == 1) {
1272 unsigned j = IsLE ? 0 : 2;
1273 for (unsigned i = 0; i != 8; i += 2)
1274 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1275 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1276 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1277 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1283 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1284 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1285 /// current subtarget.
1287 /// The ShuffleKind distinguishes between big-endian operations with
1288 /// two different inputs (0), either-endian operations with two identical
1289 /// inputs (1), and little-endian operations with two different inputs (2).
1290 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1291 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1292 SelectionDAG &DAG) {
1293 const PPCSubtarget& Subtarget =
1294 static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1295 if (!Subtarget.hasP8Vector())
1298 bool IsLE = DAG.getDataLayout().isLittleEndian();
1299 if (ShuffleKind == 0) {
1302 for (unsigned i = 0; i != 16; i += 4)
1303 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
1304 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
1305 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
1306 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
1308 } else if (ShuffleKind == 2) {
1311 for (unsigned i = 0; i != 16; i += 4)
1312 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1313 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
1314 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
1315 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
1317 } else if (ShuffleKind == 1) {
1318 unsigned j = IsLE ? 0 : 4;
1319 for (unsigned i = 0; i != 8; i += 4)
1320 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1321 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1322 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
1323 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
1324 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1325 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
1326 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1327 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1333 /// isVMerge - Common function, used to match vmrg* shuffles.
1335 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1336 unsigned LHSStart, unsigned RHSStart) {
1337 if (N->getValueType(0) != MVT::v16i8)
1339 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1340 "Unsupported merge size!");
1342 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1343 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1344 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1345 LHSStart+j+i*UnitSize) ||
1346 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1347 RHSStart+j+i*UnitSize))
1353 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1354 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1355 /// The ShuffleKind distinguishes between big-endian merges with two
1356 /// different inputs (0), either-endian merges with two identical inputs (1),
1357 /// and little-endian merges with two different inputs (2). For the latter,
1358 /// the input operands are swapped (see PPCInstrAltivec.td).
1359 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1360 unsigned ShuffleKind, SelectionDAG &DAG) {
1361 if (DAG.getDataLayout().isLittleEndian()) {
1362 if (ShuffleKind == 1) // unary
1363 return isVMerge(N, UnitSize, 0, 0);
1364 else if (ShuffleKind == 2) // swapped
1365 return isVMerge(N, UnitSize, 0, 16);
1369 if (ShuffleKind == 1) // unary
1370 return isVMerge(N, UnitSize, 8, 8);
1371 else if (ShuffleKind == 0) // normal
1372 return isVMerge(N, UnitSize, 8, 24);
1378 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1379 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1380 /// The ShuffleKind distinguishes between big-endian merges with two
1381 /// different inputs (0), either-endian merges with two identical inputs (1),
1382 /// and little-endian merges with two different inputs (2). For the latter,
1383 /// the input operands are swapped (see PPCInstrAltivec.td).
1384 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1385 unsigned ShuffleKind, SelectionDAG &DAG) {
1386 if (DAG.getDataLayout().isLittleEndian()) {
1387 if (ShuffleKind == 1) // unary
1388 return isVMerge(N, UnitSize, 8, 8);
1389 else if (ShuffleKind == 2) // swapped
1390 return isVMerge(N, UnitSize, 8, 24);
1394 if (ShuffleKind == 1) // unary
1395 return isVMerge(N, UnitSize, 0, 0);
1396 else if (ShuffleKind == 0) // normal
1397 return isVMerge(N, UnitSize, 0, 16);
1404 * \brief Common function used to match vmrgew and vmrgow shuffles
1406 * The indexOffset determines whether to look for even or odd words in
1407 * the shuffle mask. This is based on the of the endianness of the target
1410 * - Use offset of 0 to check for odd elements
1411 * - Use offset of 4 to check for even elements
1413 * - Use offset of 0 to check for even elements
1414 * - Use offset of 4 to check for odd elements
1415 * A detailed description of the vector element ordering for little endian and
1416 * big endian can be found at
1417 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1418 * Targeting your applications - what little endian and big endian IBM XL C/C++
1419 * compiler differences mean to you
1421 * The mask to the shuffle vector instruction specifies the indices of the
1422 * elements from the two input vectors to place in the result. The elements are
1423 * numbered in array-access order, starting with the first vector. These vectors
1424 * are always of type v16i8, thus each vector will contain 16 elements of size
1425 * 8. More info on the shuffle vector can be found in the
1426 * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1427 * Language Reference.
1429 * The RHSStartValue indicates whether the same input vectors are used (unary)
1430 * or two different input vectors are used, based on the following:
1431 * - If the instruction uses the same vector for both inputs, the range of the
1432 * indices will be 0 to 15. In this case, the RHSStart value passed should
1434 * - If the instruction has two different vectors then the range of the
1435 * indices will be 0 to 31. In this case, the RHSStart value passed should
1436 * be 16 (indices 0-15 specify elements in the first vector while indices 16
1437 * to 31 specify elements in the second vector).
1439 * \param[in] N The shuffle vector SD Node to analyze
1440 * \param[in] IndexOffset Specifies whether to look for even or odd elements
1441 * \param[in] RHSStartValue Specifies the starting index for the righthand input
1442 * vector to the shuffle_vector instruction
1443 * \return true iff this shuffle vector represents an even or odd word merge
1445 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1446 unsigned RHSStartValue) {
1447 if (N->getValueType(0) != MVT::v16i8)
1450 for (unsigned i = 0; i < 2; ++i)
1451 for (unsigned j = 0; j < 4; ++j)
1452 if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1453 i*RHSStartValue+j+IndexOffset) ||
1454 !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1455 i*RHSStartValue+j+IndexOffset+8))
1461 * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1462 * vmrgow instructions.
1464 * \param[in] N The shuffle vector SD Node to analyze
1465 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1466 * \param[in] ShuffleKind Identify the type of merge:
1467 * - 0 = big-endian merge with two different inputs;
1468 * - 1 = either-endian merge with two identical inputs;
1469 * - 2 = little-endian merge with two different inputs (inputs are swapped for
1470 * little-endian merges).
1471 * \param[in] DAG The current SelectionDAG
1472 * \return true iff this shuffle mask
1474 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1475 unsigned ShuffleKind, SelectionDAG &DAG) {
1476 if (DAG.getDataLayout().isLittleEndian()) {
1477 unsigned indexOffset = CheckEven ? 4 : 0;
1478 if (ShuffleKind == 1) // Unary
1479 return isVMerge(N, indexOffset, 0);
1480 else if (ShuffleKind == 2) // swapped
1481 return isVMerge(N, indexOffset, 16);
1486 unsigned indexOffset = CheckEven ? 0 : 4;
1487 if (ShuffleKind == 1) // Unary
1488 return isVMerge(N, indexOffset, 0);
1489 else if (ShuffleKind == 0) // Normal
1490 return isVMerge(N, indexOffset, 16);
1497 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1498 /// amount, otherwise return -1.
1499 /// The ShuffleKind distinguishes between big-endian operations with two
1500 /// different inputs (0), either-endian operations with two identical inputs
1501 /// (1), and little-endian operations with two different inputs (2). For the
1502 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1503 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1504 SelectionDAG &DAG) {
1505 if (N->getValueType(0) != MVT::v16i8)
1508 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1510 // Find the first non-undef value in the shuffle mask.
1512 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1515 if (i == 16) return -1; // all undef.
1517 // Otherwise, check to see if the rest of the elements are consecutively
1518 // numbered from this value.
1519 unsigned ShiftAmt = SVOp->getMaskElt(i);
1520 if (ShiftAmt < i) return -1;
1523 bool isLE = DAG.getDataLayout().isLittleEndian();
1525 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1526 // Check the rest of the elements to see if they are consecutive.
1527 for (++i; i != 16; ++i)
1528 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1530 } else if (ShuffleKind == 1) {
1531 // Check the rest of the elements to see if they are consecutive.
1532 for (++i; i != 16; ++i)
1533 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1539 ShiftAmt = 16 - ShiftAmt;
1544 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1545 /// specifies a splat of a single element that is suitable for input to
1546 /// VSPLTB/VSPLTH/VSPLTW.
1547 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1548 assert(N->getValueType(0) == MVT::v16i8 &&
1549 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1551 // The consecutive indices need to specify an element, not part of two
1552 // different elements. So abandon ship early if this isn't the case.
1553 if (N->getMaskElt(0) % EltSize != 0)
1556 // This is a splat operation if each element of the permute is the same, and
1557 // if the value doesn't reference the second vector.
1558 unsigned ElementBase = N->getMaskElt(0);
1560 // FIXME: Handle UNDEF elements too!
1561 if (ElementBase >= 16)
1564 // Check that the indices are consecutive, in the case of a multi-byte element
1565 // splatted with a v16i8 mask.
1566 for (unsigned i = 1; i != EltSize; ++i)
1567 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1570 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1571 if (N->getMaskElt(i) < 0) continue;
1572 for (unsigned j = 0; j != EltSize; ++j)
1573 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1579 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1580 unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1581 // Check that the mask is shuffling words
1582 for (unsigned i = 0; i < 4; ++i) {
1583 unsigned B0 = N->getMaskElt(i*4);
1584 unsigned B1 = N->getMaskElt(i*4+1);
1585 unsigned B2 = N->getMaskElt(i*4+2);
1586 unsigned B3 = N->getMaskElt(i*4+3);
1589 if (B1 != B0+1 || B2 != B1+1 || B3 != B2+1)
1593 // Now we look at mask elements 0,4,8,12
1594 unsigned M0 = N->getMaskElt(0) / 4;
1595 unsigned M1 = N->getMaskElt(4) / 4;
1596 unsigned M2 = N->getMaskElt(8) / 4;
1597 unsigned M3 = N->getMaskElt(12) / 4;
1598 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1599 unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1601 // Below, let H and L be arbitrary elements of the shuffle mask
1602 // where H is in the range [4,7] and L is in the range [0,3].
1603 // H, 1, 2, 3 or L, 5, 6, 7
1604 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1605 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1606 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1607 InsertAtByte = IsLE ? 12 : 0;
1611 // 0, H, 2, 3 or 4, L, 6, 7
1612 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1613 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1614 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1615 InsertAtByte = IsLE ? 8 : 4;
1619 // 0, 1, H, 3 or 4, 5, L, 7
1620 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1621 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1622 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1623 InsertAtByte = IsLE ? 4 : 8;
1627 // 0, 1, 2, H or 4, 5, 6, L
1628 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1629 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1630 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1631 InsertAtByte = IsLE ? 0 : 12;
1636 // If both vector operands for the shuffle are the same vector, the mask will
1637 // contain only elements from the first one and the second one will be undef.
1638 if (N->getOperand(1).isUndef()) {
1641 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1642 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1643 InsertAtByte = IsLE ? 12 : 0;
1646 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1647 InsertAtByte = IsLE ? 8 : 4;
1650 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1651 InsertAtByte = IsLE ? 4 : 8;
1654 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1655 InsertAtByte = IsLE ? 0 : 12;
1663 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1664 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1665 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1666 SelectionDAG &DAG) {
1667 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1668 assert(isSplatShuffleMask(SVOp, EltSize));
1669 if (DAG.getDataLayout().isLittleEndian())
1670 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1672 return SVOp->getMaskElt(0) / EltSize;
1675 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1676 /// by using a vspltis[bhw] instruction of the specified element size, return
1677 /// the constant being splatted. The ByteSize field indicates the number of
1678 /// bytes of each element [124] -> [bhw].
1679 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1680 SDValue OpVal(nullptr, 0);
1682 // If ByteSize of the splat is bigger than the element size of the
1683 // build_vector, then we have a case where we are checking for a splat where
1684 // multiple elements of the buildvector are folded together into a single
1685 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1686 unsigned EltSize = 16/N->getNumOperands();
1687 if (EltSize < ByteSize) {
1688 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1689 SDValue UniquedVals[4];
1690 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1692 // See if all of the elements in the buildvector agree across.
1693 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1694 if (N->getOperand(i).isUndef()) continue;
1695 // If the element isn't a constant, bail fully out.
1696 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1698 if (!UniquedVals[i&(Multiple-1)].getNode())
1699 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1700 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1701 return SDValue(); // no match.
1704 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1705 // either constant or undef values that are identical for each chunk. See
1706 // if these chunks can form into a larger vspltis*.
1708 // Check to see if all of the leading entries are either 0 or -1. If
1709 // neither, then this won't fit into the immediate field.
1710 bool LeadingZero = true;
1711 bool LeadingOnes = true;
1712 for (unsigned i = 0; i != Multiple-1; ++i) {
1713 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1715 LeadingZero &= isNullConstant(UniquedVals[i]);
1716 LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1718 // Finally, check the least significant entry.
1720 if (!UniquedVals[Multiple-1].getNode())
1721 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
1722 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1723 if (Val < 16) // 0,0,0,4 -> vspltisw(4)
1724 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1727 if (!UniquedVals[Multiple-1].getNode())
1728 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1729 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1730 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1731 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1737 // Check to see if this buildvec has a single non-undef value in its elements.
1738 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1739 if (N->getOperand(i).isUndef()) continue;
1740 if (!OpVal.getNode())
1741 OpVal = N->getOperand(i);
1742 else if (OpVal != N->getOperand(i))
1746 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1748 unsigned ValSizeInBytes = EltSize;
1750 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1751 Value = CN->getZExtValue();
1752 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1753 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1754 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1757 // If the splat value is larger than the element value, then we can never do
1758 // this splat. The only case that we could fit the replicated bits into our
1759 // immediate field for would be zero, and we prefer to use vxor for it.
1760 if (ValSizeInBytes < ByteSize) return SDValue();
1762 // If the element value is larger than the splat value, check if it consists
1763 // of a repeated bit pattern of size ByteSize.
1764 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1767 // Properly sign extend the value.
1768 int MaskVal = SignExtend32(Value, ByteSize * 8);
1770 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1771 if (MaskVal == 0) return SDValue();
1773 // Finally, if this value fits in a 5 bit sext field, return it
1774 if (SignExtend32<5>(MaskVal) == MaskVal)
1775 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1779 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1780 /// amount, otherwise return -1.
1781 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1782 EVT VT = N->getValueType(0);
1783 if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1786 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1788 // Find the first non-undef value in the shuffle mask.
1790 for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1793 if (i == 4) return -1; // all undef.
1795 // Otherwise, check to see if the rest of the elements are consecutively
1796 // numbered from this value.
1797 unsigned ShiftAmt = SVOp->getMaskElt(i);
1798 if (ShiftAmt < i) return -1;
1801 // Check the rest of the elements to see if they are consecutive.
1802 for (++i; i != 4; ++i)
1803 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1809 //===----------------------------------------------------------------------===//
1810 // Addressing Mode Selection
1811 //===----------------------------------------------------------------------===//
1813 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1814 /// or 64-bit immediate, and if the value can be accurately represented as a
1815 /// sign extension from a 16-bit value. If so, this returns true and the
1817 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1818 if (!isa<ConstantSDNode>(N))
1821 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1822 if (N->getValueType(0) == MVT::i32)
1823 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1825 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1827 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1828 return isIntS16Immediate(Op.getNode(), Imm);
1831 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1832 /// can be represented as an indexed [r+r] operation. Returns false if it
1833 /// can be more efficiently represented with [r+imm].
1834 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1836 SelectionDAG &DAG) const {
1838 if (N.getOpcode() == ISD::ADD) {
1839 if (isIntS16Immediate(N.getOperand(1), imm))
1840 return false; // r+i
1841 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1842 return false; // r+i
1844 Base = N.getOperand(0);
1845 Index = N.getOperand(1);
1847 } else if (N.getOpcode() == ISD::OR) {
1848 if (isIntS16Immediate(N.getOperand(1), imm))
1849 return false; // r+i can fold it if we can.
1851 // If this is an or of disjoint bitfields, we can codegen this as an add
1852 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1854 KnownBits LHSKnown, RHSKnown;
1855 DAG.computeKnownBits(N.getOperand(0), LHSKnown);
1857 if (LHSKnown.Zero.getBoolValue()) {
1858 DAG.computeKnownBits(N.getOperand(1), RHSKnown);
1859 // If all of the bits are known zero on the LHS or RHS, the add won't
1861 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
1862 Base = N.getOperand(0);
1863 Index = N.getOperand(1);
1872 // If we happen to be doing an i64 load or store into a stack slot that has
1873 // less than a 4-byte alignment, then the frame-index elimination may need to
1874 // use an indexed load or store instruction (because the offset may not be a
1875 // multiple of 4). The extra register needed to hold the offset comes from the
1876 // register scavenger, and it is possible that the scavenger will need to use
1877 // an emergency spill slot. As a result, we need to make sure that a spill slot
1878 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1880 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1881 // FIXME: This does not handle the LWA case.
1885 // NOTE: We'll exclude negative FIs here, which come from argument
1886 // lowering, because there are no known test cases triggering this problem
1887 // using packed structures (or similar). We can remove this exclusion if
1888 // we find such a test case. The reason why this is so test-case driven is
1889 // because this entire 'fixup' is only to prevent crashes (from the
1890 // register scavenger) on not-really-valid inputs. For example, if we have:
1892 // %b = bitcast i1* %a to i64*
1893 // store i64* a, i64 b
1894 // then the store should really be marked as 'align 1', but is not. If it
1895 // were marked as 'align 1' then the indexed form would have been
1896 // instruction-selected initially, and the problem this 'fixup' is preventing
1897 // won't happen regardless.
1901 MachineFunction &MF = DAG.getMachineFunction();
1902 MachineFrameInfo &MFI = MF.getFrameInfo();
1904 unsigned Align = MFI.getObjectAlignment(FrameIdx);
1908 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1909 FuncInfo->setHasNonRISpills();
1912 /// Returns true if the address N can be represented by a base register plus
1913 /// a signed 16-bit displacement [r+imm], and if it is not better
1914 /// represented as reg+reg. If Aligned is true, only accept displacements
1915 /// suitable for STD and friends, i.e. multiples of 4.
1916 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1919 bool Aligned) const {
1920 // FIXME dl should come from parent load or store, not from address
1922 // If this can be more profitably realized as r+r, fail.
1923 if (SelectAddressRegReg(N, Disp, Base, DAG))
1926 if (N.getOpcode() == ISD::ADD) {
1928 if (isIntS16Immediate(N.getOperand(1), imm) &&
1929 (!Aligned || (imm & 3) == 0)) {
1930 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1931 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1932 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1933 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1935 Base = N.getOperand(0);
1937 return true; // [r+i]
1938 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1939 // Match LOAD (ADD (X, Lo(G))).
1940 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1941 && "Cannot handle constant offsets yet!");
1942 Disp = N.getOperand(1).getOperand(0); // The global address.
1943 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1944 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1945 Disp.getOpcode() == ISD::TargetConstantPool ||
1946 Disp.getOpcode() == ISD::TargetJumpTable);
1947 Base = N.getOperand(0);
1948 return true; // [&g+r]
1950 } else if (N.getOpcode() == ISD::OR) {
1952 if (isIntS16Immediate(N.getOperand(1), imm) &&
1953 (!Aligned || (imm & 3) == 0)) {
1954 // If this is an or of disjoint bitfields, we can codegen this as an add
1955 // (for better address arithmetic) if the LHS and RHS of the OR are
1956 // provably disjoint.
1958 DAG.computeKnownBits(N.getOperand(0), LHSKnown);
1960 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1961 // If all of the bits are known zero on the LHS or RHS, the add won't
1963 if (FrameIndexSDNode *FI =
1964 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1965 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1966 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1968 Base = N.getOperand(0);
1970 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1974 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1975 // Loading from a constant address.
1977 // If this address fits entirely in a 16-bit sext immediate field, codegen
1980 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1981 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
1982 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1983 CN->getValueType(0));
1987 // Handle 32-bit sext immediates with LIS + addr mode.
1988 if ((CN->getValueType(0) == MVT::i32 ||
1989 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1990 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1991 int Addr = (int)CN->getZExtValue();
1993 // Otherwise, break this down into an LIS + disp.
1994 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
1996 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
1998 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1999 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2004 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2005 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2006 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2007 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2010 return true; // [r+0]
2013 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2014 /// represented as an indexed [r+r] operation.
2015 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2017 SelectionDAG &DAG) const {
2018 // Check to see if we can easily represent this as an [r+r] address. This
2019 // will fail if it thinks that the address is more profitably represented as
2020 // reg+imm, e.g. where imm = 0.
2021 if (SelectAddressRegReg(N, Base, Index, DAG))
2024 // If the operand is an addition, always emit this as [r+r], since this is
2025 // better (for code size, and execution, as the memop does the add for free)
2026 // than emitting an explicit add.
2027 if (N.getOpcode() == ISD::ADD) {
2028 Base = N.getOperand(0);
2029 Index = N.getOperand(1);
2033 // Otherwise, do it the hard way, using R0 as the base register.
2034 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2040 /// getPreIndexedAddressParts - returns true by value, base pointer and
2041 /// offset pointer and addressing mode by reference if the node's address
2042 /// can be legally represented as pre-indexed load / store address.
2043 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2045 ISD::MemIndexedMode &AM,
2046 SelectionDAG &DAG) const {
2047 if (DisablePPCPreinc) return false;
2053 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2054 Ptr = LD->getBasePtr();
2055 VT = LD->getMemoryVT();
2056 Alignment = LD->getAlignment();
2057 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2058 Ptr = ST->getBasePtr();
2059 VT = ST->getMemoryVT();
2060 Alignment = ST->getAlignment();
2065 // PowerPC doesn't have preinc load/store instructions for vectors (except
2066 // for QPX, which does have preinc r+r forms).
2067 if (VT.isVector()) {
2068 if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2070 } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2076 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2077 // Common code will reject creating a pre-inc form if the base pointer
2078 // is a frame index, or if N is a store and the base pointer is either
2079 // the same as or a predecessor of the value being stored. Check for
2080 // those situations here, and try with swapped Base/Offset instead.
2083 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2086 SDValue Val = cast<StoreSDNode>(N)->getValue();
2087 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2092 std::swap(Base, Offset);
2098 // LDU/STU can only handle immediates that are a multiple of 4.
2099 if (VT != MVT::i64) {
2100 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
2103 // LDU/STU need an address with at least 4-byte alignment.
2107 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
2111 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2112 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
2113 // sext i32 to i64 when addr mode is r+i.
2114 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2115 LD->getExtensionType() == ISD::SEXTLOAD &&
2116 isa<ConstantSDNode>(Offset))
2124 //===----------------------------------------------------------------------===//
2125 // LowerOperation implementation
2126 //===----------------------------------------------------------------------===//
2128 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2129 /// and LoOpFlags to the target MO flags.
2130 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2131 unsigned &HiOpFlags, unsigned &LoOpFlags,
2132 const GlobalValue *GV = nullptr) {
2133 HiOpFlags = PPCII::MO_HA;
2134 LoOpFlags = PPCII::MO_LO;
2136 // Don't use the pic base if not in PIC relocation model.
2138 HiOpFlags |= PPCII::MO_PIC_FLAG;
2139 LoOpFlags |= PPCII::MO_PIC_FLAG;
2142 // If this is a reference to a global value that requires a non-lazy-ptr, make
2143 // sure that instruction lowering adds it.
2144 if (GV && Subtarget.hasLazyResolverStub(GV)) {
2145 HiOpFlags |= PPCII::MO_NLP_FLAG;
2146 LoOpFlags |= PPCII::MO_NLP_FLAG;
2148 if (GV->hasHiddenVisibility()) {
2149 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2150 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2155 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2156 SelectionDAG &DAG) {
2158 EVT PtrVT = HiPart.getValueType();
2159 SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2161 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2162 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2164 // With PIC, the first instruction is actually "GR+hi(&G)".
2166 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2167 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2169 // Generate non-pic code that has direct accesses to the constant pool.
2170 // The address of the global is just (hi(&g)+lo(&g)).
2171 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2174 static void setUsesTOCBasePtr(MachineFunction &MF) {
2175 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2176 FuncInfo->setUsesTOCBasePtr();
2179 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2180 setUsesTOCBasePtr(DAG.getMachineFunction());
2183 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2185 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2186 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2187 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2189 SDValue Ops[] = { GA, Reg };
2190 return DAG.getMemIntrinsicNode(
2191 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2192 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2196 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2197 SelectionDAG &DAG) const {
2198 EVT PtrVT = Op.getValueType();
2199 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2200 const Constant *C = CP->getConstVal();
2202 // 64-bit SVR4 ABI code is always position-independent.
2203 // The actual address of the GlobalValue is stored in the TOC.
2204 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2205 setUsesTOCBasePtr(DAG);
2206 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2207 return getTOCEntry(DAG, SDLoc(CP), true, GA);
2210 unsigned MOHiFlag, MOLoFlag;
2211 bool IsPIC = isPositionIndependent();
2212 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2214 if (IsPIC && Subtarget.isSVR4ABI()) {
2215 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2216 PPCII::MO_PIC_FLAG);
2217 return getTOCEntry(DAG, SDLoc(CP), false, GA);
2221 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2223 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2224 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2227 // For 64-bit PowerPC, prefer the more compact relative encodings.
2228 // This trades 32 bits per jump table entry for one or two instructions
2229 // on the jump site.
2230 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2231 if (isJumpTableRelative())
2232 return MachineJumpTableInfo::EK_LabelDifference32;
2234 return TargetLowering::getJumpTableEncoding();
2237 bool PPCTargetLowering::isJumpTableRelative() const {
2238 if (Subtarget.isPPC64())
2240 return TargetLowering::isJumpTableRelative();
2243 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2244 SelectionDAG &DAG) const {
2245 if (!Subtarget.isPPC64())
2246 return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2248 switch (getTargetMachine().getCodeModel()) {
2249 case CodeModel::Default:
2250 case CodeModel::Small:
2251 case CodeModel::Medium:
2252 return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2254 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2255 getPointerTy(DAG.getDataLayout()));
2260 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2262 MCContext &Ctx) const {
2263 if (!Subtarget.isPPC64())
2264 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2266 switch (getTargetMachine().getCodeModel()) {
2267 case CodeModel::Default:
2268 case CodeModel::Small:
2269 case CodeModel::Medium:
2270 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2272 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2276 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2277 EVT PtrVT = Op.getValueType();
2278 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2280 // 64-bit SVR4 ABI code is always position-independent.
2281 // The actual address of the GlobalValue is stored in the TOC.
2282 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2283 setUsesTOCBasePtr(DAG);
2284 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2285 return getTOCEntry(DAG, SDLoc(JT), true, GA);
2288 unsigned MOHiFlag, MOLoFlag;
2289 bool IsPIC = isPositionIndependent();
2290 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2292 if (IsPIC && Subtarget.isSVR4ABI()) {
2293 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2294 PPCII::MO_PIC_FLAG);
2295 return getTOCEntry(DAG, SDLoc(GA), false, GA);
2298 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2299 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2300 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2303 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2304 SelectionDAG &DAG) const {
2305 EVT PtrVT = Op.getValueType();
2306 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2307 const BlockAddress *BA = BASDN->getBlockAddress();
2309 // 64-bit SVR4 ABI code is always position-independent.
2310 // The actual BlockAddress is stored in the TOC.
2311 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2312 setUsesTOCBasePtr(DAG);
2313 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2314 return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2317 unsigned MOHiFlag, MOLoFlag;
2318 bool IsPIC = isPositionIndependent();
2319 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2320 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2321 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2322 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2325 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2326 SelectionDAG &DAG) const {
2327 // FIXME: TLS addresses currently use medium model code sequences,
2328 // which is the most useful form. Eventually support for small and
2329 // large models could be added if users need it, at the cost of
2330 // additional complexity.
2331 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2332 if (DAG.getTarget().Options.EmulatedTLS)
2333 return LowerToTLSEmulatedModel(GA, DAG);
2336 const GlobalValue *GV = GA->getGlobal();
2337 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2338 bool is64bit = Subtarget.isPPC64();
2339 const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2340 PICLevel::Level picLevel = M->getPICLevel();
2342 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2344 if (Model == TLSModel::LocalExec) {
2345 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2346 PPCII::MO_TPREL_HA);
2347 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2348 PPCII::MO_TPREL_LO);
2349 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2350 is64bit ? MVT::i64 : MVT::i32);
2351 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2352 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2355 if (Model == TLSModel::InitialExec) {
2356 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2357 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2361 setUsesTOCBasePtr(DAG);
2362 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2363 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2364 PtrVT, GOTReg, TGA);
2366 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2367 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2368 PtrVT, TGA, GOTPtr);
2369 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2372 if (Model == TLSModel::GeneralDynamic) {
2373 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2376 setUsesTOCBasePtr(DAG);
2377 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2378 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2381 if (picLevel == PICLevel::SmallPIC)
2382 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2384 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2386 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2390 if (Model == TLSModel::LocalDynamic) {
2391 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2394 setUsesTOCBasePtr(DAG);
2395 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2396 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2399 if (picLevel == PICLevel::SmallPIC)
2400 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2402 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2404 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2405 PtrVT, GOTPtr, TGA, TGA);
2406 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2407 PtrVT, TLSAddr, TGA);
2408 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2411 llvm_unreachable("Unknown TLS model!");
2414 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2415 SelectionDAG &DAG) const {
2416 EVT PtrVT = Op.getValueType();
2417 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2419 const GlobalValue *GV = GSDN->getGlobal();
2421 // 64-bit SVR4 ABI code is always position-independent.
2422 // The actual address of the GlobalValue is stored in the TOC.
2423 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2424 setUsesTOCBasePtr(DAG);
2425 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2426 return getTOCEntry(DAG, DL, true, GA);
2429 unsigned MOHiFlag, MOLoFlag;
2430 bool IsPIC = isPositionIndependent();
2431 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2433 if (IsPIC && Subtarget.isSVR4ABI()) {
2434 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2436 PPCII::MO_PIC_FLAG);
2437 return getTOCEntry(DAG, DL, false, GA);
2441 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2443 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2445 SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2447 // If the global reference is actually to a non-lazy-pointer, we have to do an
2448 // extra load to get the address of the global.
2449 if (MOHiFlag & PPCII::MO_NLP_FLAG)
2450 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2454 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2455 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2458 if (Op.getValueType() == MVT::v2i64) {
2459 // When the operands themselves are v2i64 values, we need to do something
2460 // special because VSX has no underlying comparison operations for these.
2461 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2462 // Equality can be handled by casting to the legal type for Altivec
2463 // comparisons, everything else needs to be expanded.
2464 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2465 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2466 DAG.getSetCC(dl, MVT::v4i32,
2467 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2468 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2475 // We handle most of these in the usual way.
2479 // If we're comparing for equality to zero, expose the fact that this is
2480 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2481 // fold the new nodes.
2482 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2485 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2486 // Leave comparisons against 0 and -1 alone for now, since they're usually
2487 // optimized. FIXME: revisit this when we can custom lower all setcc
2489 if (C->isAllOnesValue() || C->isNullValue())
2493 // If we have an integer seteq/setne, turn it into a compare against zero
2494 // by xor'ing the rhs with the lhs, which is faster than setting a
2495 // condition register, reading it back out, and masking the correct bit. The
2496 // normal approach here uses sub to do this instead of xor. Using xor exposes
2497 // the result to other bit-twiddling opportunities.
2498 EVT LHSVT = Op.getOperand(0).getValueType();
2499 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2500 EVT VT = Op.getValueType();
2501 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2503 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2508 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2509 SDNode *Node = Op.getNode();
2510 EVT VT = Node->getValueType(0);
2511 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2512 SDValue InChain = Node->getOperand(0);
2513 SDValue VAListPtr = Node->getOperand(1);
2514 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2517 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2520 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2521 VAListPtr, MachinePointerInfo(SV), MVT::i8);
2522 InChain = GprIndex.getValue(1);
2524 if (VT == MVT::i64) {
2525 // Check if GprIndex is even
2526 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2527 DAG.getConstant(1, dl, MVT::i32));
2528 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2529 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2530 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2531 DAG.getConstant(1, dl, MVT::i32));
2532 // Align GprIndex to be even if it isn't
2533 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2537 // fpr index is 1 byte after gpr
2538 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2539 DAG.getConstant(1, dl, MVT::i32));
2542 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2543 FprPtr, MachinePointerInfo(SV), MVT::i8);
2544 InChain = FprIndex.getValue(1);
2546 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2547 DAG.getConstant(8, dl, MVT::i32));
2549 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2550 DAG.getConstant(4, dl, MVT::i32));
2553 SDValue OverflowArea =
2554 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2555 InChain = OverflowArea.getValue(1);
2557 SDValue RegSaveArea =
2558 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2559 InChain = RegSaveArea.getValue(1);
2561 // select overflow_area if index > 8
2562 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2563 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2565 // adjustment constant gpr_index * 4/8
2566 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2567 VT.isInteger() ? GprIndex : FprIndex,
2568 DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2571 // OurReg = RegSaveArea + RegConstant
2572 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2575 // Floating types are 32 bytes into RegSaveArea
2576 if (VT.isFloatingPoint())
2577 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2578 DAG.getConstant(32, dl, MVT::i32));
2580 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2581 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2582 VT.isInteger() ? GprIndex : FprIndex,
2583 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2586 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2587 VT.isInteger() ? VAListPtr : FprPtr,
2588 MachinePointerInfo(SV), MVT::i8);
2590 // determine if we should load from reg_save_area or overflow_area
2591 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2593 // increase overflow_area by 4/8 if gpr/fpr > 8
2594 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2595 DAG.getConstant(VT.isInteger() ? 4 : 8,
2598 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2601 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2602 MachinePointerInfo(), MVT::i32);
2604 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2607 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2608 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2610 // We have to copy the entire va_list struct:
2611 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2612 return DAG.getMemcpy(Op.getOperand(0), Op,
2613 Op.getOperand(1), Op.getOperand(2),
2614 DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2615 false, MachinePointerInfo(), MachinePointerInfo());
2618 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2619 SelectionDAG &DAG) const {
2620 return Op.getOperand(0);
2623 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2624 SelectionDAG &DAG) const {
2625 SDValue Chain = Op.getOperand(0);
2626 SDValue Trmp = Op.getOperand(1); // trampoline
2627 SDValue FPtr = Op.getOperand(2); // nested function
2628 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2631 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2632 bool isPPC64 = (PtrVT == MVT::i64);
2633 Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2635 TargetLowering::ArgListTy Args;
2636 TargetLowering::ArgListEntry Entry;
2638 Entry.Ty = IntPtrTy;
2639 Entry.Node = Trmp; Args.push_back(Entry);
2641 // TrampSize == (isPPC64 ? 48 : 40);
2642 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2643 isPPC64 ? MVT::i64 : MVT::i32);
2644 Args.push_back(Entry);
2646 Entry.Node = FPtr; Args.push_back(Entry);
2647 Entry.Node = Nest; Args.push_back(Entry);
2649 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2650 TargetLowering::CallLoweringInfo CLI(DAG);
2651 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2652 CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2653 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
2655 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2656 return CallResult.second;
2659 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2660 MachineFunction &MF = DAG.getMachineFunction();
2661 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2662 EVT PtrVT = getPointerTy(MF.getDataLayout());
2666 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2667 // vastart just stores the address of the VarArgsFrameIndex slot into the
2668 // memory location argument.
2669 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2670 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2671 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2672 MachinePointerInfo(SV));
2675 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2676 // We suppose the given va_list is already allocated.
2679 // char gpr; /* index into the array of 8 GPRs
2680 // * stored in the register save area
2681 // * gpr=0 corresponds to r3,
2682 // * gpr=1 to r4, etc.
2684 // char fpr; /* index into the array of 8 FPRs
2685 // * stored in the register save area
2686 // * fpr=0 corresponds to f1,
2687 // * fpr=1 to f2, etc.
2689 // char *overflow_arg_area;
2690 // /* location on stack that holds
2691 // * the next overflow argument
2693 // char *reg_save_area;
2694 // /* where r3:r10 and f1:f8 (if saved)
2699 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2700 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2701 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2703 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2706 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2707 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2709 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2710 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2712 uint64_t FPROffset = 1;
2713 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2715 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2717 // Store first byte : number of int regs
2718 SDValue firstStore =
2719 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
2720 MachinePointerInfo(SV), MVT::i8);
2721 uint64_t nextOffset = FPROffset;
2722 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2725 // Store second byte : number of float regs
2726 SDValue secondStore =
2727 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2728 MachinePointerInfo(SV, nextOffset), MVT::i8);
2729 nextOffset += StackOffset;
2730 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2732 // Store second word : arguments given on stack
2733 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2734 MachinePointerInfo(SV, nextOffset));
2735 nextOffset += FrameOffset;
2736 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2738 // Store third word : arguments given in registers
2739 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2740 MachinePointerInfo(SV, nextOffset));
2743 #include "PPCGenCallingConv.inc"
2745 // Function whose sole purpose is to kill compiler warnings
2746 // stemming from unused functions included from PPCGenCallingConv.inc.
2747 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2748 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2751 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2752 CCValAssign::LocInfo &LocInfo,
2753 ISD::ArgFlagsTy &ArgFlags,
2758 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2760 CCValAssign::LocInfo &LocInfo,
2761 ISD::ArgFlagsTy &ArgFlags,
2763 static const MCPhysReg ArgRegs[] = {
2764 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2765 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2767 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2769 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2771 // Skip one register if the first unallocated register has an even register
2772 // number and there are still argument registers available which have not been
2773 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2774 // need to skip a register if RegNum is odd.
2775 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2776 State.AllocateReg(ArgRegs[RegNum]);
2779 // Always return false here, as this function only makes sure that the first
2780 // unallocated register has an odd register number and does not actually
2781 // allocate a register for the current argument.
2786 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT,
2788 CCValAssign::LocInfo &LocInfo,
2789 ISD::ArgFlagsTy &ArgFlags,
2791 static const MCPhysReg ArgRegs[] = {
2792 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2793 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2795 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2797 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2798 int RegsLeft = NumArgRegs - RegNum;
2800 // Skip if there is not enough registers left for long double type (4 gpr regs
2801 // in soft float mode) and put long double argument on the stack.
2802 if (RegNum != NumArgRegs && RegsLeft < 4) {
2803 for (int i = 0; i < RegsLeft; i++) {
2804 State.AllocateReg(ArgRegs[RegNum + i]);
2811 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2813 CCValAssign::LocInfo &LocInfo,
2814 ISD::ArgFlagsTy &ArgFlags,
2816 static const MCPhysReg ArgRegs[] = {
2817 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2821 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2823 unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2825 // If there is only one Floating-point register left we need to put both f64
2826 // values of a split ppc_fp128 value on the stack.
2827 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2828 State.AllocateReg(ArgRegs[RegNum]);
2831 // Always return false here, as this function only makes sure that the two f64
2832 // values a ppc_fp128 value is split into are both passed in registers or both
2833 // passed on the stack and does not actually allocate a register for the
2834 // current argument.
2838 /// FPR - The set of FP registers that should be allocated for arguments,
2840 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
2841 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
2842 PPC::F11, PPC::F12, PPC::F13};
2844 /// QFPR - The set of QPX registers that should be allocated for arguments.
2845 static const MCPhysReg QFPR[] = {
2846 PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7,
2847 PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2849 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2851 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2852 unsigned PtrByteSize) {
2853 unsigned ArgSize = ArgVT.getStoreSize();
2854 if (Flags.isByVal())
2855 ArgSize = Flags.getByValSize();
2857 // Round up to multiples of the pointer size, except for array members,
2858 // which are always packed.
2859 if (!Flags.isInConsecutiveRegs())
2860 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2865 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2867 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2868 ISD::ArgFlagsTy Flags,
2869 unsigned PtrByteSize) {
2870 unsigned Align = PtrByteSize;
2872 // Altivec parameters are padded to a 16 byte boundary.
2873 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2874 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2875 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2876 ArgVT == MVT::v1i128)
2878 // QPX vector types stored in double-precision are padded to a 32 byte
2880 else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2883 // ByVal parameters are aligned as requested.
2884 if (Flags.isByVal()) {
2885 unsigned BVAlign = Flags.getByValAlign();
2886 if (BVAlign > PtrByteSize) {
2887 if (BVAlign % PtrByteSize != 0)
2889 "ByVal alignment is not a multiple of the pointer size");
2895 // Array members are always packed to their original alignment.
2896 if (Flags.isInConsecutiveRegs()) {
2897 // If the array member was split into multiple registers, the first
2898 // needs to be aligned to the size of the full type. (Except for
2899 // ppcf128, which is only aligned as its f64 components.)
2900 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2901 Align = OrigVT.getStoreSize();
2903 Align = ArgVT.getStoreSize();
2909 /// CalculateStackSlotUsed - Return whether this argument will use its
2910 /// stack slot (instead of being passed in registers). ArgOffset,
2911 /// AvailableFPRs, and AvailableVRs must hold the current argument
2912 /// position, and will be updated to account for this argument.
2913 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2914 ISD::ArgFlagsTy Flags,
2915 unsigned PtrByteSize,
2916 unsigned LinkageSize,
2917 unsigned ParamAreaSize,
2918 unsigned &ArgOffset,
2919 unsigned &AvailableFPRs,
2920 unsigned &AvailableVRs, bool HasQPX) {
2921 bool UseMemory = false;
2923 // Respect alignment of argument on the stack.
2925 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2926 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2927 // If there's no space left in the argument save area, we must
2928 // use memory (this check also catches zero-sized arguments).
2929 if (ArgOffset >= LinkageSize + ParamAreaSize)
2932 // Allocate argument on the stack.
2933 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2934 if (Flags.isInConsecutiveRegsLast())
2935 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2936 // If we overran the argument save area, we must use memory
2937 // (this check catches arguments passed partially in memory)
2938 if (ArgOffset > LinkageSize + ParamAreaSize)
2941 // However, if the argument is actually passed in an FPR or a VR,
2942 // we don't use memory after all.
2943 if (!Flags.isByVal()) {
2944 if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2945 // QPX registers overlap with the scalar FP registers.
2946 (HasQPX && (ArgVT == MVT::v4f32 ||
2947 ArgVT == MVT::v4f64 ||
2948 ArgVT == MVT::v4i1)))
2949 if (AvailableFPRs > 0) {
2953 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2954 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2955 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2956 ArgVT == MVT::v1i128)
2957 if (AvailableVRs > 0) {
2966 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2967 /// ensure minimum alignment required for target.
2968 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2969 unsigned NumBytes) {
2970 unsigned TargetAlign = Lowering->getStackAlignment();
2971 unsigned AlignMask = TargetAlign - 1;
2972 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2976 SDValue PPCTargetLowering::LowerFormalArguments(
2977 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2978 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2979 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2980 if (Subtarget.isSVR4ABI()) {
2981 if (Subtarget.isPPC64())
2982 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2985 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2988 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2993 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
2994 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2995 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2996 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2998 // 32-bit SVR4 ABI Stack Frame Layout:
2999 // +-----------------------------------+
3000 // +--> | Back chain |
3001 // | +-----------------------------------+
3002 // | | Floating-point register save area |
3003 // | +-----------------------------------+
3004 // | | General register save area |
3005 // | +-----------------------------------+
3006 // | | CR save word |
3007 // | +-----------------------------------+
3008 // | | VRSAVE save word |
3009 // | +-----------------------------------+
3010 // | | Alignment padding |
3011 // | +-----------------------------------+
3012 // | | Vector register save area |
3013 // | +-----------------------------------+
3014 // | | Local variable space |
3015 // | +-----------------------------------+
3016 // | | Parameter list area |
3017 // | +-----------------------------------+
3018 // | | LR save word |
3019 // | +-----------------------------------+
3020 // SP--> +--- | Back chain |
3021 // +-----------------------------------+
3024 // System V Application Binary Interface PowerPC Processor Supplement
3025 // AltiVec Technology Programming Interface Manual
3027 MachineFunction &MF = DAG.getMachineFunction();
3028 MachineFrameInfo &MFI = MF.getFrameInfo();
3029 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3031 EVT PtrVT = getPointerTy(MF.getDataLayout());
3032 // Potential tail calls could cause overwriting of argument stack slots.
3033 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3034 (CallConv == CallingConv::Fast));
3035 unsigned PtrByteSize = 4;
3037 // Assign locations to all of the incoming arguments.
3038 SmallVector<CCValAssign, 16> ArgLocs;
3039 PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3042 // Reserve space for the linkage area on the stack.
3043 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3044 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3046 CCInfo.PreAnalyzeFormalArguments(Ins);
3048 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3049 CCInfo.clearWasPPCF128();
3051 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3052 CCValAssign &VA = ArgLocs[i];
3054 // Arguments stored in registers.
3055 if (VA.isRegLoc()) {
3056 const TargetRegisterClass *RC;
3057 EVT ValVT = VA.getValVT();
3059 switch (ValVT.getSimpleVT().SimpleTy) {
3061 llvm_unreachable("ValVT not supported by formal arguments Lowering");
3064 RC = &PPC::GPRCRegClass;
3067 if (Subtarget.hasP8Vector())
3068 RC = &PPC::VSSRCRegClass;
3070 RC = &PPC::F4RCRegClass;
3073 if (Subtarget.hasVSX())
3074 RC = &PPC::VSFRCRegClass;
3076 RC = &PPC::F8RCRegClass;
3081 RC = &PPC::VRRCRegClass;
3084 RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3088 RC = &PPC::VRRCRegClass;
3091 RC = &PPC::QFRCRegClass;
3094 RC = &PPC::QBRCRegClass;
3098 // Transform the arguments stored in physical registers into virtual ones.
3099 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3100 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3101 ValVT == MVT::i1 ? MVT::i32 : ValVT);
3103 if (ValVT == MVT::i1)
3104 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3106 InVals.push_back(ArgValue);
3108 // Argument stored in memory.
3109 assert(VA.isMemLoc());
3111 unsigned ArgSize = VA.getLocVT().getStoreSize();
3112 int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(),
3115 // Create load nodes to retrieve arguments from the stack.
3116 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3118 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3122 // Assign locations to all of the incoming aggregate by value arguments.
3123 // Aggregates passed by value are stored in the local variable space of the
3124 // caller's stack frame, right above the parameter list area.
3125 SmallVector<CCValAssign, 16> ByValArgLocs;
3126 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3127 ByValArgLocs, *DAG.getContext());
3129 // Reserve stack space for the allocations in CCInfo.
3130 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3132 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3134 // Area that is at least reserved in the caller of this function.
3135 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3136 MinReservedArea = std::max(MinReservedArea, LinkageSize);
3138 // Set the size that is at least reserved in caller of this function. Tail
3139 // call optimized function's reserved stack space needs to be aligned so that
3140 // taking the difference between two stack areas will result in an aligned
3143 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3144 FuncInfo->setMinReservedArea(MinReservedArea);
3146 SmallVector<SDValue, 8> MemOps;
3148 // If the function takes variable number of arguments, make a frame index for
3149 // the start of the first vararg value... for expansion of llvm.va_start.
3151 static const MCPhysReg GPArgRegs[] = {
3152 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3153 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3155 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3157 static const MCPhysReg FPArgRegs[] = {
3158 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3161 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3166 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3167 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3169 // Make room for NumGPArgRegs and NumFPArgRegs.
3170 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3171 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3173 FuncInfo->setVarArgsStackOffset(
3174 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3175 CCInfo.getNextStackOffset(), true));
3177 FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3178 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3180 // The fixed integer arguments of a variadic function are stored to the
3181 // VarArgsFrameIndex on the stack so that they may be loaded by
3182 // dereferencing the result of va_next.
3183 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3184 // Get an existing live-in vreg, or add a new one.
3185 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3187 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3189 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3191 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3192 MemOps.push_back(Store);
3193 // Increment the address by four for the next argument to store
3194 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3195 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3198 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3200 // The double arguments are stored to the VarArgsFrameIndex
3202 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3203 // Get an existing live-in vreg, or add a new one.
3204 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3206 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3208 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3210 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3211 MemOps.push_back(Store);
3212 // Increment the address by eight for the next argument to store
3213 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3215 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3219 if (!MemOps.empty())
3220 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3225 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3226 // value to MVT::i64 and then truncate to the correct register size.
3227 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3228 EVT ObjectVT, SelectionDAG &DAG,
3230 const SDLoc &dl) const {
3232 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3233 DAG.getValueType(ObjectVT));
3234 else if (Flags.isZExt())
3235 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3236 DAG.getValueType(ObjectVT));
3238 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3241 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3242 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3243 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3244 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3245 // TODO: add description of PPC stack frame format, or at least some docs.
3247 bool isELFv2ABI = Subtarget.isELFv2ABI();
3248 bool isLittleEndian = Subtarget.isLittleEndian();
3249 MachineFunction &MF = DAG.getMachineFunction();
3250 MachineFrameInfo &MFI = MF.getFrameInfo();
3251 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3253 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3254 "fastcc not supported on varargs functions");
3256 EVT PtrVT = getPointerTy(MF.getDataLayout());
3257 // Potential tail calls could cause overwriting of argument stack slots.
3258 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3259 (CallConv == CallingConv::Fast));
3260 unsigned PtrByteSize = 8;
3261 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3263 static const MCPhysReg GPR[] = {
3264 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3265 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3267 static const MCPhysReg VR[] = {
3268 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3269 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3272 const unsigned Num_GPR_Regs = array_lengthof(GPR);
3273 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3274 const unsigned Num_VR_Regs = array_lengthof(VR);
3275 const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3277 // Do a first pass over the arguments to determine whether the ABI
3278 // guarantees that our caller has allocated the parameter save area
3279 // on its stack frame. In the ELFv1 ABI, this is always the case;
3280 // in the ELFv2 ABI, it is true if this is a vararg function or if
3281 // any parameter is located in a stack slot.
3283 bool HasParameterArea = !isELFv2ABI || isVarArg;
3284 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3285 unsigned NumBytes = LinkageSize;
3286 unsigned AvailableFPRs = Num_FPR_Regs;
3287 unsigned AvailableVRs = Num_VR_Regs;
3288 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3289 if (Ins[i].Flags.isNest())
3292 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3293 PtrByteSize, LinkageSize, ParamAreaSize,
3294 NumBytes, AvailableFPRs, AvailableVRs,
3295 Subtarget.hasQPX()))
3296 HasParameterArea = true;
3299 // Add DAG nodes to load the arguments or copy them out of registers. On
3300 // entry to a function on PPC, the arguments start after the linkage area,
3301 // although the first ones are often in registers.
3303 unsigned ArgOffset = LinkageSize;
3304 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3305 unsigned &QFPR_idx = FPR_idx;
3306 SmallVector<SDValue, 8> MemOps;
3307 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3308 unsigned CurArgIdx = 0;
3309 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3311 bool needsLoad = false;
3312 EVT ObjectVT = Ins[ArgNo].VT;
3313 EVT OrigVT = Ins[ArgNo].ArgVT;
3314 unsigned ObjSize = ObjectVT.getStoreSize();
3315 unsigned ArgSize = ObjSize;
3316 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3317 if (Ins[ArgNo].isOrigArg()) {
3318 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3319 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3321 // We re-align the argument offset for each argument, except when using the
3322 // fast calling convention, when we need to make sure we do that only when
3323 // we'll actually use a stack slot.
3324 unsigned CurArgOffset, Align;
3325 auto ComputeArgOffset = [&]() {
3326 /* Respect alignment of argument on the stack. */
3327 Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3328 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3329 CurArgOffset = ArgOffset;
3332 if (CallConv != CallingConv::Fast) {
3335 /* Compute GPR index associated with argument offset. */
3336 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3337 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3340 // FIXME the codegen can be much improved in some cases.
3341 // We do not have to keep everything in memory.
3342 if (Flags.isByVal()) {
3343 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3345 if (CallConv == CallingConv::Fast)
3348 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3349 ObjSize = Flags.getByValSize();
3350 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3351 // Empty aggregate parameters do not take up registers. Examples:
3355 // etc. However, we have to provide a place-holder in InVals, so
3356 // pretend we have an 8-byte item at the current address for that
3359 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3360 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3361 InVals.push_back(FIN);
3365 // Create a stack object covering all stack doublewords occupied
3366 // by the argument. If the argument is (fully or partially) on
3367 // the stack, or if the argument is fully in registers but the
3368 // caller has allocated the parameter save anyway, we can refer
3369 // directly to the caller's stack frame. Otherwise, create a
3370 // local copy in our own frame.
3372 if (HasParameterArea ||
3373 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3374 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3376 FI = MFI.CreateStackObject(ArgSize, Align, false);
3377 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3379 // Handle aggregates smaller than 8 bytes.
3380 if (ObjSize < PtrByteSize) {
3381 // The value of the object is its address, which differs from the
3382 // address of the enclosing doubleword on big-endian systems.
3384 if (!isLittleEndian) {
3385 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3386 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3388 InVals.push_back(Arg);
3390 if (GPR_idx != Num_GPR_Regs) {
3391 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3392 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3395 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3396 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3397 (ObjSize == 2 ? MVT::i16 : MVT::i32));
3398 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3399 MachinePointerInfo(&*FuncArg), ObjType);
3401 // For sizes that don't fit a truncating store (3, 5, 6, 7),
3402 // store the whole register as-is to the parameter save area
3404 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3405 MachinePointerInfo(&*FuncArg));
3408 MemOps.push_back(Store);
3410 // Whether we copied from a register or not, advance the offset
3411 // into the parameter save area by a full doubleword.
3412 ArgOffset += PtrByteSize;
3416 // The value of the object is its address, which is the address of
3417 // its first stack doubleword.
3418 InVals.push_back(FIN);
3420 // Store whatever pieces of the object are in registers to memory.
3421 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3422 if (GPR_idx == Num_GPR_Regs)
3425 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3426 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3429 SDValue Off = DAG.getConstant(j, dl, PtrVT);
3430 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3432 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3433 MachinePointerInfo(&*FuncArg, j));
3434 MemOps.push_back(Store);
3437 ArgOffset += ArgSize;
3441 switch (ObjectVT.getSimpleVT().SimpleTy) {
3442 default: llvm_unreachable("Unhandled argument type!");
3446 if (Flags.isNest()) {
3447 // The 'nest' parameter, if any, is passed in R11.
3448 unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3449 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3451 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3452 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3457 // These can be scalar arguments or elements of an integer array type
3458 // passed directly. Clang may use those instead of "byval" aggregate
3459 // types to avoid forcing arguments to memory unnecessarily.
3460 if (GPR_idx != Num_GPR_Regs) {
3461 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3462 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3464 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3465 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3466 // value to MVT::i64 and then truncate to the correct register size.
3467 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3469 if (CallConv == CallingConv::Fast)
3473 ArgSize = PtrByteSize;
3475 if (CallConv != CallingConv::Fast || needsLoad)
3481 // These can be scalar arguments or elements of a float array type
3482 // passed directly. The latter are used to implement ELFv2 homogenous
3483 // float aggregates.
3484 if (FPR_idx != Num_FPR_Regs) {
3487 if (ObjectVT == MVT::f32)
3488 VReg = MF.addLiveIn(FPR[FPR_idx],
3489 Subtarget.hasP8Vector()
3490 ? &PPC::VSSRCRegClass
3491 : &PPC::F4RCRegClass);
3493 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3494 ? &PPC::VSFRCRegClass
3495 : &PPC::F8RCRegClass);
3497 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3499 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3500 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3501 // once we support fp <-> gpr moves.
3503 // This can only ever happen in the presence of f32 array types,
3504 // since otherwise we never run out of FPRs before running out
3506 unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3507 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3509 if (ObjectVT == MVT::f32) {
3510 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3511 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3512 DAG.getConstant(32, dl, MVT::i32));
3513 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3516 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3518 if (CallConv == CallingConv::Fast)
3524 // When passing an array of floats, the array occupies consecutive
3525 // space in the argument area; only round up to the next doubleword
3526 // at the end of the array. Otherwise, each float takes 8 bytes.
3527 if (CallConv != CallingConv::Fast || needsLoad) {
3528 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3529 ArgOffset += ArgSize;
3530 if (Flags.isInConsecutiveRegsLast())
3531 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3541 if (!Subtarget.hasQPX()) {
3542 // These can be scalar arguments or elements of a vector array type
3543 // passed directly. The latter are used to implement ELFv2 homogenous
3544 // vector aggregates.
3545 if (VR_idx != Num_VR_Regs) {
3546 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3547 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3550 if (CallConv == CallingConv::Fast)
3555 if (CallConv != CallingConv::Fast || needsLoad)
3560 assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3561 "Invalid QPX parameter type");
3566 // QPX vectors are treated like their scalar floating-point subregisters
3567 // (except that they're larger).
3568 unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3569 if (QFPR_idx != Num_QFPR_Regs) {
3570 const TargetRegisterClass *RC;
3571 switch (ObjectVT.getSimpleVT().SimpleTy) {
3572 case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3573 case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3574 default: RC = &PPC::QBRCRegClass; break;
3577 unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3578 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3581 if (CallConv == CallingConv::Fast)
3585 if (CallConv != CallingConv::Fast || needsLoad)
3590 // We need to load the argument to a virtual register if we determined
3591 // above that we ran out of physical registers of the appropriate type.
3593 if (ObjSize < ArgSize && !isLittleEndian)
3594 CurArgOffset += ArgSize - ObjSize;
3595 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3596 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3597 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3600 InVals.push_back(ArgVal);
3603 // Area that is at least reserved in the caller of this function.
3604 unsigned MinReservedArea;
3605 if (HasParameterArea)
3606 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3608 MinReservedArea = LinkageSize;
3610 // Set the size that is at least reserved in caller of this function. Tail
3611 // call optimized functions' reserved stack space needs to be aligned so that
3612 // taking the difference between two stack areas will result in an aligned
3615 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3616 FuncInfo->setMinReservedArea(MinReservedArea);
3618 // If the function takes variable number of arguments, make a frame index for
3619 // the start of the first vararg value... for expansion of llvm.va_start.
3621 int Depth = ArgOffset;
3623 FuncInfo->setVarArgsFrameIndex(
3624 MFI.CreateFixedObject(PtrByteSize, Depth, true));
3625 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3627 // If this function is vararg, store any remaining integer argument regs
3628 // to their spots on the stack so that they may be loaded by dereferencing
3629 // the result of va_next.
3630 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3631 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3632 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3633 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3635 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3636 MemOps.push_back(Store);
3637 // Increment the address by four for the next argument to store
3638 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3639 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3643 if (!MemOps.empty())
3644 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3649 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3650 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3651 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3652 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3653 // TODO: add description of PPC stack frame format, or at least some docs.
3655 MachineFunction &MF = DAG.getMachineFunction();
3656 MachineFrameInfo &MFI = MF.getFrameInfo();
3657 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3659 EVT PtrVT = getPointerTy(MF.getDataLayout());
3660 bool isPPC64 = PtrVT == MVT::i64;
3661 // Potential tail calls could cause overwriting of argument stack slots.
3662 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3663 (CallConv == CallingConv::Fast));
3664 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3665 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3666 unsigned ArgOffset = LinkageSize;
3667 // Area that is at least reserved in caller of this function.
3668 unsigned MinReservedArea = ArgOffset;
3670 static const MCPhysReg GPR_32[] = { // 32-bit registers.
3671 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3672 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3674 static const MCPhysReg GPR_64[] = { // 64-bit registers.
3675 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3676 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3678 static const MCPhysReg VR[] = {
3679 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3680 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3683 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3684 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3685 const unsigned Num_VR_Regs = array_lengthof( VR);
3687 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3689 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3691 // In 32-bit non-varargs functions, the stack space for vectors is after the
3692 // stack space for non-vectors. We do not use this space unless we have
3693 // too many vectors to fit in registers, something that only occurs in
3694 // constructed examples:), but we have to walk the arglist to figure
3695 // that out...for the pathological case, compute VecArgOffset as the
3696 // start of the vector parameter area. Computing VecArgOffset is the
3697 // entire point of the following loop.
3698 unsigned VecArgOffset = ArgOffset;
3699 if (!isVarArg && !isPPC64) {
3700 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3702 EVT ObjectVT = Ins[ArgNo].VT;
3703 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3705 if (Flags.isByVal()) {
3706 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3707 unsigned ObjSize = Flags.getByValSize();
3709 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3710 VecArgOffset += ArgSize;
3714 switch(ObjectVT.getSimpleVT().SimpleTy) {
3715 default: llvm_unreachable("Unhandled argument type!");
3721 case MVT::i64: // PPC64
3723 // FIXME: We are guaranteed to be !isPPC64 at this point.
3724 // Does MVT::i64 apply?
3731 // Nothing to do, we're only looking at Nonvector args here.
3736 // We've found where the vector parameter area in memory is. Skip the
3737 // first 12 parameters; these don't use that memory.
3738 VecArgOffset = ((VecArgOffset+15)/16)*16;
3739 VecArgOffset += 12*16;
3741 // Add DAG nodes to load the arguments or copy them out of registers. On
3742 // entry to a function on PPC, the arguments start after the linkage area,
3743 // although the first ones are often in registers.
3745 SmallVector<SDValue, 8> MemOps;
3746 unsigned nAltivecParamsAtEnd = 0;
3747 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3748 unsigned CurArgIdx = 0;
3749 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3751 bool needsLoad = false;
3752 EVT ObjectVT = Ins[ArgNo].VT;
3753 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3754 unsigned ArgSize = ObjSize;
3755 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3756 if (Ins[ArgNo].isOrigArg()) {
3757 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3758 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3760 unsigned CurArgOffset = ArgOffset;
3762 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3763 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3764 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3765 if (isVarArg || isPPC64) {
3766 MinReservedArea = ((MinReservedArea+15)/16)*16;
3767 MinReservedArea += CalculateStackSlotSize(ObjectVT,
3770 } else nAltivecParamsAtEnd++;
3772 // Calculate min reserved area.
3773 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3777 // FIXME the codegen can be much improved in some cases.
3778 // We do not have to keep everything in memory.
3779 if (Flags.isByVal()) {
3780 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3782 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3783 ObjSize = Flags.getByValSize();
3784 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3785 // Objects of size 1 and 2 are right justified, everything else is
3786 // left justified. This means the memory address is adjusted forwards.
3787 if (ObjSize==1 || ObjSize==2) {
3788 CurArgOffset = CurArgOffset + (4 - ObjSize);
3790 // The value of the object is its address.
3791 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
3792 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3793 InVals.push_back(FIN);
3794 if (ObjSize==1 || ObjSize==2) {
3795 if (GPR_idx != Num_GPR_Regs) {
3798 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3800 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3801 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3802 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3804 DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3805 MachinePointerInfo(&*FuncArg), ObjType);
3806 MemOps.push_back(Store);
3810 ArgOffset += PtrByteSize;
3814 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3815 // Store whatever pieces of the object are in registers
3816 // to memory. ArgOffset will be the address of the beginning
3818 if (GPR_idx != Num_GPR_Regs) {
3821 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3823 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3824 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3825 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3826 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3827 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3828 MachinePointerInfo(&*FuncArg, j));
3829 MemOps.push_back(Store);
3831 ArgOffset += PtrByteSize;
3833 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3840 switch (ObjectVT.getSimpleVT().SimpleTy) {
3841 default: llvm_unreachable("Unhandled argument type!");
3845 if (GPR_idx != Num_GPR_Regs) {
3846 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3847 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3849 if (ObjectVT == MVT::i1)
3850 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3855 ArgSize = PtrByteSize;
3857 // All int arguments reserve stack space in the Darwin ABI.
3858 ArgOffset += PtrByteSize;
3862 case MVT::i64: // PPC64
3863 if (GPR_idx != Num_GPR_Regs) {
3864 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3865 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3867 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3868 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3869 // value to MVT::i64 and then truncate to the correct register size.
3870 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3875 ArgSize = PtrByteSize;
3877 // All int arguments reserve stack space in the Darwin ABI.
3883 // Every 4 bytes of argument space consumes one of the GPRs available for
3884 // argument passing.
3885 if (GPR_idx != Num_GPR_Regs) {
3887 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3890 if (FPR_idx != Num_FPR_Regs) {
3893 if (ObjectVT == MVT::f32)
3894 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3896 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3898 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3904 // All FP arguments reserve stack space in the Darwin ABI.
3905 ArgOffset += isPPC64 ? 8 : ObjSize;
3911 // Note that vector arguments in registers don't reserve stack space,
3912 // except in varargs functions.
3913 if (VR_idx != Num_VR_Regs) {
3914 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3915 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3917 while ((ArgOffset % 16) != 0) {
3918 ArgOffset += PtrByteSize;
3919 if (GPR_idx != Num_GPR_Regs)
3923 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3927 if (!isVarArg && !isPPC64) {
3928 // Vectors go after all the nonvectors.
3929 CurArgOffset = VecArgOffset;
3932 // Vectors are aligned.
3933 ArgOffset = ((ArgOffset+15)/16)*16;
3934 CurArgOffset = ArgOffset;
3942 // We need to load the argument to a virtual register if we determined above
3943 // that we ran out of physical registers of the appropriate type.
3945 int FI = MFI.CreateFixedObject(ObjSize,
3946 CurArgOffset + (ArgSize - ObjSize),
3948 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3949 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3952 InVals.push_back(ArgVal);
3955 // Allow for Altivec parameters at the end, if needed.
3956 if (nAltivecParamsAtEnd) {
3957 MinReservedArea = ((MinReservedArea+15)/16)*16;
3958 MinReservedArea += 16*nAltivecParamsAtEnd;
3961 // Area that is at least reserved in the caller of this function.
3962 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3964 // Set the size that is at least reserved in caller of this function. Tail
3965 // call optimized functions' reserved stack space needs to be aligned so that
3966 // taking the difference between two stack areas will result in an aligned
3969 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3970 FuncInfo->setMinReservedArea(MinReservedArea);
3972 // If the function takes variable number of arguments, make a frame index for
3973 // the start of the first vararg value... for expansion of llvm.va_start.
3975 int Depth = ArgOffset;
3977 FuncInfo->setVarArgsFrameIndex(
3978 MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3980 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3982 // If this function is vararg, store any remaining integer argument regs
3983 // to their spots on the stack so that they may be loaded by dereferencing
3984 // the result of va_next.
3985 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3989 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3991 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3993 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3995 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3996 MemOps.push_back(Store);
3997 // Increment the address by four for the next argument to store
3998 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3999 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4003 if (!MemOps.empty())
4004 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4009 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4010 /// adjusted to accommodate the arguments for the tailcall.
4011 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4012 unsigned ParamSize) {
4014 if (!isTailCall) return 0;
4016 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4017 unsigned CallerMinReservedArea = FI->getMinReservedArea();
4018 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4019 // Remember only if the new adjustement is bigger.
4020 if (SPDiff < FI->getTailCallSPDelta())
4021 FI->setTailCallSPDelta(SPDiff);
4026 static bool isFunctionGlobalAddress(SDValue Callee);
4029 resideInSameSection(const Function *Caller, SDValue Callee,
4030 const TargetMachine &TM) {
4031 // If !G, Callee can be an external symbol.
4032 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4036 const GlobalValue *GV = G->getGlobal();
4037 if (!GV->isStrongDefinitionForLinker())
4040 // Any explicitly-specified sections and section prefixes must also match.
4041 // Also, if we're using -ffunction-sections, then each function is always in
4042 // a different section (the same is true for COMDAT functions).
4043 if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4044 GV->getSection() != Caller->getSection())
4046 if (const auto *F = dyn_cast<Function>(GV)) {
4047 if (F->getSectionPrefix() != Caller->getSectionPrefix())
4051 // If the callee might be interposed, then we can't assume the ultimate call
4052 // target will be in the same section. Even in cases where we can assume that
4053 // interposition won't happen, in any case where the linker might insert a
4054 // stub to allow for interposition, we must generate code as though
4055 // interposition might occur. To understand why this matters, consider a
4056 // situation where: a -> b -> c where the arrows indicate calls. b and c are
4057 // in the same section, but a is in a different module (i.e. has a different
4058 // TOC base pointer). If the linker allows for interposition between b and c,
4059 // then it will generate a stub for the call edge between b and c which will
4060 // save the TOC pointer into the designated stack slot allocated by b. If we
4061 // return true here, and therefore allow a tail call between b and c, that
4062 // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4063 // pointer into the stack slot allocated by a (where the a -> b stub saved
4064 // a's TOC base pointer). If we're not considering a tail call, but rather,
4065 // whether a nop is needed after the call instruction in b, because the linker
4066 // will insert a stub, it might complain about a missing nop if we omit it
4067 // (although many don't complain in this case).
4068 if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4075 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4076 const SmallVectorImpl<ISD::OutputArg> &Outs) {
4077 assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
4079 const unsigned PtrByteSize = 8;
4080 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4082 static const MCPhysReg GPR[] = {
4083 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4084 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4086 static const MCPhysReg VR[] = {
4087 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4088 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4091 const unsigned NumGPRs = array_lengthof(GPR);
4092 const unsigned NumFPRs = 13;
4093 const unsigned NumVRs = array_lengthof(VR);
4094 const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4096 unsigned NumBytes = LinkageSize;
4097 unsigned AvailableFPRs = NumFPRs;
4098 unsigned AvailableVRs = NumVRs;
4100 for (const ISD::OutputArg& Param : Outs) {
4101 if (Param.Flags.isNest()) continue;
4103 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4104 PtrByteSize, LinkageSize, ParamAreaSize,
4105 NumBytes, AvailableFPRs, AvailableVRs,
4106 Subtarget.hasQPX()))
4113 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite *CS) {
4114 if (CS->arg_size() != CallerFn->arg_size())
4117 ImmutableCallSite::arg_iterator CalleeArgIter = CS->arg_begin();
4118 ImmutableCallSite::arg_iterator CalleeArgEnd = CS->arg_end();
4119 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4121 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4122 const Value* CalleeArg = *CalleeArgIter;
4123 const Value* CallerArg = &(*CallerArgIter);
4124 if (CalleeArg == CallerArg)
4127 // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4128 // tail call @callee([4 x i64] undef, [4 x i64] %b)
4130 // 1st argument of callee is undef and has the same type as caller.
4131 if (CalleeArg->getType() == CallerArg->getType() &&
4132 isa<UndefValue>(CalleeArg))
4142 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4144 CallingConv::ID CalleeCC,
4145 ImmutableCallSite *CS,
4147 const SmallVectorImpl<ISD::OutputArg> &Outs,
4148 const SmallVectorImpl<ISD::InputArg> &Ins,
4149 SelectionDAG& DAG) const {
4150 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4152 if (DisableSCO && !TailCallOpt) return false;
4154 // Variadic argument functions are not supported.
4155 if (isVarArg) return false;
4157 MachineFunction &MF = DAG.getMachineFunction();
4158 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4160 // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has
4161 // the same calling convention
4162 if (CallerCC != CalleeCC) return false;
4164 // SCO support C calling convention
4165 if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C)
4168 // Caller contains any byval parameter is not supported.
4169 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4172 // Callee contains any byval parameter is not supported, too.
4173 // Note: This is a quick work around, because in some cases, e.g.
4174 // caller's stack size > callee's stack size, we are still able to apply
4175 // sibling call optimization. See: https://reviews.llvm.org/D23441#513574
4176 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4179 // No TCO/SCO on indirect call because Caller have to restore its TOC
4180 if (!isFunctionGlobalAddress(Callee) &&
4181 !isa<ExternalSymbolSDNode>(Callee))
4184 // Check if Callee resides in the same section, because for now, PPC64 SVR4
4185 // ABI (ELFv1/ELFv2) doesn't allow tail calls to a symbol resides in another
4187 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4188 if (!resideInSameSection(MF.getFunction(), Callee, getTargetMachine()))
4191 // TCO allows altering callee ABI, so we don't have to check further.
4192 if (CalleeCC == CallingConv::Fast && TailCallOpt)
4195 if (DisableSCO) return false;
4197 // If callee use the same argument list that caller is using, then we can
4198 // apply SCO on this case. If it is not, then we need to check if callee needs
4199 // stack for passing arguments.
4200 if (!hasSameArgumentList(MF.getFunction(), CS) &&
4201 needStackSlotPassParameters(Subtarget, Outs)) {
4208 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4209 /// for tail call optimization. Targets which want to do tail call
4210 /// optimization should implement this function.
4212 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4213 CallingConv::ID CalleeCC,
4215 const SmallVectorImpl<ISD::InputArg> &Ins,
4216 SelectionDAG& DAG) const {
4217 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4220 // Variable argument functions are not supported.
4224 MachineFunction &MF = DAG.getMachineFunction();
4225 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4226 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4227 // Functions containing by val parameters are not supported.
4228 for (unsigned i = 0; i != Ins.size(); i++) {
4229 ISD::ArgFlagsTy Flags = Ins[i].Flags;
4230 if (Flags.isByVal()) return false;
4233 // Non-PIC/GOT tail calls are supported.
4234 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4237 // At the moment we can only do local tail calls (in same module, hidden
4238 // or protected) if we are generating PIC.
4239 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4240 return G->getGlobal()->hasHiddenVisibility()
4241 || G->getGlobal()->hasProtectedVisibility();
4247 /// isCallCompatibleAddress - Return the immediate to use if the specified
4248 /// 32-bit value is representable in the immediate field of a BxA instruction.
4249 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4250 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4251 if (!C) return nullptr;
4253 int Addr = C->getZExtValue();
4254 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
4255 SignExtend32<26>(Addr) != Addr)
4256 return nullptr; // Top 6 bits have to be sext of immediate.
4260 (int)C->getZExtValue() >> 2, SDLoc(Op),
4261 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4267 struct TailCallArgumentInfo {
4272 TailCallArgumentInfo() = default;
4275 } // end anonymous namespace
4277 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4278 static void StoreTailCallArgumentsToStackSlot(
4279 SelectionDAG &DAG, SDValue Chain,
4280 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4281 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4282 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4283 SDValue Arg = TailCallArgs[i].Arg;
4284 SDValue FIN = TailCallArgs[i].FrameIdxOp;
4285 int FI = TailCallArgs[i].FrameIdx;
4286 // Store relative to framepointer.
4287 MemOpChains.push_back(DAG.getStore(
4288 Chain, dl, Arg, FIN,
4289 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4293 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4294 /// the appropriate stack slot for the tail call optimized function call.
4295 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4296 SDValue OldRetAddr, SDValue OldFP,
4297 int SPDiff, const SDLoc &dl) {
4299 // Calculate the new stack slot for the return address.
4300 MachineFunction &MF = DAG.getMachineFunction();
4301 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4302 const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4303 bool isPPC64 = Subtarget.isPPC64();
4304 int SlotSize = isPPC64 ? 8 : 4;
4305 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4306 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4307 NewRetAddrLoc, true);
4308 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4309 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4310 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4311 MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4313 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4314 // slot as the FP is never overwritten.
4315 if (Subtarget.isDarwinABI()) {
4316 int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4317 int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4319 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4320 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4321 MachinePointerInfo::getFixedStack(
4322 DAG.getMachineFunction(), NewFPIdx));
4328 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4329 /// the position of the argument.
4331 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4332 SDValue Arg, int SPDiff, unsigned ArgOffset,
4333 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4334 int Offset = ArgOffset + SPDiff;
4335 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4336 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4337 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4338 SDValue FIN = DAG.getFrameIndex(FI, VT);
4339 TailCallArgumentInfo Info;
4341 Info.FrameIdxOp = FIN;
4343 TailCallArguments.push_back(Info);
4346 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4347 /// stack slot. Returns the chain as result and the loaded frame pointers in
4348 /// LROpOut/FPOpout. Used when tail calling.
4349 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4350 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4351 SDValue &FPOpOut, const SDLoc &dl) const {
4353 // Load the LR and FP stack slot for later adjusting.
4354 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4355 LROpOut = getReturnAddrFrameIndex(DAG);
4356 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4357 Chain = SDValue(LROpOut.getNode(), 1);
4359 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4360 // slot as the FP is never overwritten.
4361 if (Subtarget.isDarwinABI()) {
4362 FPOpOut = getFramePointerFrameIndex(DAG);
4363 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4364 Chain = SDValue(FPOpOut.getNode(), 1);
4370 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4371 /// by "Src" to address "Dst" of size "Size". Alignment information is
4372 /// specified by the specific parameter attribute. The copy will be passed as
4373 /// a byval function parameter.
4374 /// Sometimes what we are copying is the end of a larger object, the part that
4375 /// does not fit in registers.
4376 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4377 SDValue Chain, ISD::ArgFlagsTy Flags,
4378 SelectionDAG &DAG, const SDLoc &dl) {
4379 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4380 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4381 false, false, false, MachinePointerInfo(),
4382 MachinePointerInfo());
4385 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4387 static void LowerMemOpCallTo(
4388 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4389 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4390 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4391 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4392 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4397 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4399 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4400 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4401 DAG.getConstant(ArgOffset, dl, PtrVT));
4403 MemOpChains.push_back(
4404 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4405 // Calculate and remember argument location.
4406 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4411 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4412 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4414 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4415 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4416 // might overwrite each other in case of tail call optimization.
4417 SmallVector<SDValue, 8> MemOpChains2;
4418 // Do not flag preceding copytoreg stuff together with the following stuff.
4420 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4422 if (!MemOpChains2.empty())
4423 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4425 // Store the return address to the appropriate stack slot.
4426 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4428 // Emit callseq_end just before tailcall node.
4429 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4430 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4431 InFlag = Chain.getValue(1);
4434 // Is this global address that of a function that can be called by name? (as
4435 // opposed to something that must hold a descriptor for an indirect call).
4436 static bool isFunctionGlobalAddress(SDValue Callee) {
4437 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4438 if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4439 Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4442 return G->getGlobal()->getValueType()->isFunctionTy();
4449 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4450 SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4451 bool isPatchPoint, bool hasNest,
4452 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4453 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4454 ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4455 bool isPPC64 = Subtarget.isPPC64();
4456 bool isSVR4ABI = Subtarget.isSVR4ABI();
4457 bool isELFv2ABI = Subtarget.isELFv2ABI();
4459 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4460 NodeTys.push_back(MVT::Other); // Returns a chain
4461 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
4463 unsigned CallOpc = PPCISD::CALL;
4465 bool needIndirectCall = true;
4466 if (!isSVR4ABI || !isPPC64)
4467 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4468 // If this is an absolute destination address, use the munged value.
4469 Callee = SDValue(Dest, 0);
4470 needIndirectCall = false;
4473 // PC-relative references to external symbols should go through $stub, unless
4474 // we're building with the leopard linker or later, which automatically
4475 // synthesizes these stubs.
4476 const TargetMachine &TM = DAG.getTarget();
4477 const Module *Mod = DAG.getMachineFunction().getFunction()->getParent();
4478 const GlobalValue *GV = nullptr;
4479 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4480 GV = G->getGlobal();
4481 bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4482 bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4484 if (isFunctionGlobalAddress(Callee)) {
4485 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4486 // A call to a TLS address is actually an indirect call to a
4487 // thread-specific pointer.
4488 unsigned OpFlags = 0;
4490 OpFlags = PPCII::MO_PLT;
4492 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4493 // every direct call is) turn it into a TargetGlobalAddress /
4494 // TargetExternalSymbol node so that legalize doesn't hack it.
4495 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4496 Callee.getValueType(), 0, OpFlags);
4497 needIndirectCall = false;
4500 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4501 unsigned char OpFlags = 0;
4504 OpFlags = PPCII::MO_PLT;
4506 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4508 needIndirectCall = false;
4512 // We'll form an invalid direct call when lowering a patchpoint; the full
4513 // sequence for an indirect call is complicated, and many of the
4514 // instructions introduced might have side effects (and, thus, can't be
4515 // removed later). The call itself will be removed as soon as the
4516 // argument/return lowering is complete, so the fact that it has the wrong
4517 // kind of operands should not really matter.
4518 needIndirectCall = false;
4521 if (needIndirectCall) {
4522 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
4523 // to do the call, we can't use PPCISD::CALL.
4524 SDValue MTCTROps[] = {Chain, Callee, InFlag};
4526 if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4527 // Function pointers in the 64-bit SVR4 ABI do not point to the function
4528 // entry point, but to the function descriptor (the function entry point
4529 // address is part of the function descriptor though).
4530 // The function descriptor is a three doubleword structure with the
4531 // following fields: function entry point, TOC base address and
4532 // environment pointer.
4533 // Thus for a call through a function pointer, the following actions need
4535 // 1. Save the TOC of the caller in the TOC save area of its stack
4536 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4537 // 2. Load the address of the function entry point from the function
4539 // 3. Load the TOC of the callee from the function descriptor into r2.
4540 // 4. Load the environment pointer from the function descriptor into
4542 // 5. Branch to the function entry point address.
4543 // 6. On return of the callee, the TOC of the caller needs to be
4544 // restored (this is done in FinishCall()).
4546 // The loads are scheduled at the beginning of the call sequence, and the
4547 // register copies are flagged together to ensure that no other
4548 // operations can be scheduled in between. E.g. without flagging the
4549 // copies together, a TOC access in the caller could be scheduled between
4550 // the assignment of the callee TOC and the branch to the callee, which
4551 // results in the TOC access going through the TOC of the callee instead
4552 // of going through the TOC of the caller, which leads to incorrect code.
4554 // Load the address of the function entry point from the function
4556 SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4557 if (LDChain.getValueType() == MVT::Glue)
4558 LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4560 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4561 ? (MachineMemOperand::MODereferenceable |
4562 MachineMemOperand::MOInvariant)
4563 : MachineMemOperand::MONone;
4565 MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4566 SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4567 /* Alignment = */ 8, MMOFlags);
4569 // Load environment pointer into r11.
4570 SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4571 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4572 SDValue LoadEnvPtr =
4573 DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4574 /* Alignment = */ 8, MMOFlags);
4576 SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4577 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4579 DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4580 /* Alignment = */ 8, MMOFlags);
4582 setUsesTOCBasePtr(DAG);
4583 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4585 Chain = TOCVal.getValue(0);
4586 InFlag = TOCVal.getValue(1);
4588 // If the function call has an explicit 'nest' parameter, it takes the
4589 // place of the environment pointer.
4591 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4594 Chain = EnvVal.getValue(0);
4595 InFlag = EnvVal.getValue(1);
4598 MTCTROps[0] = Chain;
4599 MTCTROps[1] = LoadFuncPtr;
4600 MTCTROps[2] = InFlag;
4603 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4604 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4605 InFlag = Chain.getValue(1);
4608 NodeTys.push_back(MVT::Other);
4609 NodeTys.push_back(MVT::Glue);
4610 Ops.push_back(Chain);
4611 CallOpc = PPCISD::BCTRL;
4612 Callee.setNode(nullptr);
4613 // Add use of X11 (holding environment pointer)
4614 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4615 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4616 // Add CTR register as callee so a bctr can be emitted later.
4618 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4621 // If this is a direct call, pass the chain and the callee.
4622 if (Callee.getNode()) {
4623 Ops.push_back(Chain);
4624 Ops.push_back(Callee);
4626 // If this is a tail call add stack pointer delta.
4628 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4630 // Add argument registers to the end of the list so that they are known live
4632 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4633 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4634 RegsToPass[i].second.getValueType()));
4636 // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4638 if (isSVR4ABI && isPPC64 && !isPatchPoint) {
4639 setUsesTOCBasePtr(DAG);
4640 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4646 SDValue PPCTargetLowering::LowerCallResult(
4647 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4648 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4649 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4650 SmallVector<CCValAssign, 16> RVLocs;
4651 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4653 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4655 // Copy all of the result registers out of their specified physreg.
4656 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4657 CCValAssign &VA = RVLocs[i];
4658 assert(VA.isRegLoc() && "Can only return in registers!");
4660 SDValue Val = DAG.getCopyFromReg(Chain, dl,
4661 VA.getLocReg(), VA.getLocVT(), InFlag);
4662 Chain = Val.getValue(1);
4663 InFlag = Val.getValue(2);
4665 switch (VA.getLocInfo()) {
4666 default: llvm_unreachable("Unknown loc info!");
4667 case CCValAssign::Full: break;
4668 case CCValAssign::AExt:
4669 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4671 case CCValAssign::ZExt:
4672 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4673 DAG.getValueType(VA.getValVT()));
4674 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4676 case CCValAssign::SExt:
4677 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4678 DAG.getValueType(VA.getValVT()));
4679 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4683 InVals.push_back(Val);
4689 SDValue PPCTargetLowering::FinishCall(
4690 CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
4691 bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
4692 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
4693 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
4694 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
4695 SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const {
4696 std::vector<EVT> NodeTys;
4697 SmallVector<SDValue, 8> Ops;
4698 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4699 SPDiff, isTailCall, isPatchPoint, hasNest,
4700 RegsToPass, Ops, NodeTys, CS, Subtarget);
4702 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4703 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4704 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4706 // When performing tail call optimization the callee pops its arguments off
4707 // the stack. Account for this here so these bytes can be pushed back on in
4708 // PPCFrameLowering::eliminateCallFramePseudoInstr.
4709 int BytesCalleePops =
4710 (CallConv == CallingConv::Fast &&
4711 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4713 // Add a register mask operand representing the call-preserved registers.
4714 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4715 const uint32_t *Mask =
4716 TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4717 assert(Mask && "Missing call preserved mask for calling convention");
4718 Ops.push_back(DAG.getRegisterMask(Mask));
4720 if (InFlag.getNode())
4721 Ops.push_back(InFlag);
4725 assert(((Callee.getOpcode() == ISD::Register &&
4726 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4727 Callee.getOpcode() == ISD::TargetExternalSymbol ||
4728 Callee.getOpcode() == ISD::TargetGlobalAddress ||
4729 isa<ConstantSDNode>(Callee)) &&
4730 "Expecting an global address, external symbol, absolute value or register");
4732 DAG.getMachineFunction().getFrameInfo().setHasTailCall();
4733 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4736 // Add a NOP immediately after the branch instruction when using the 64-bit
4737 // SVR4 ABI. At link time, if caller and callee are in a different module and
4738 // thus have a different TOC, the call will be replaced with a call to a stub
4739 // function which saves the current TOC, loads the TOC of the callee and
4740 // branches to the callee. The NOP will be replaced with a load instruction
4741 // which restores the TOC of the caller from the TOC save slot of the current
4742 // stack frame. If caller and callee belong to the same module (and have the
4743 // same TOC), the NOP will remain unchanged.
4745 MachineFunction &MF = DAG.getMachineFunction();
4746 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4748 if (CallOpc == PPCISD::BCTRL) {
4749 // This is a call through a function pointer.
4750 // Restore the caller TOC from the save area into R2.
4751 // See PrepareCall() for more information about calls through function
4752 // pointers in the 64-bit SVR4 ABI.
4753 // We are using a target-specific load with r2 hard coded, because the
4754 // result of a target-independent load would never go directly into r2,
4755 // since r2 is a reserved register (which prevents the register allocator
4756 // from allocating it), resulting in an additional register being
4757 // allocated and an unnecessary move instruction being generated.
4758 CallOpc = PPCISD::BCTRL_LOAD_TOC;
4760 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4761 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4762 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4763 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4764 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4766 // The address needs to go after the chain input but before the flag (or
4767 // any other variadic arguments).
4768 Ops.insert(std::next(Ops.begin()), AddTOC);
4769 } else if (CallOpc == PPCISD::CALL &&
4770 !resideInSameSection(MF.getFunction(), Callee, DAG.getTarget())) {
4771 // Otherwise insert NOP for non-local calls.
4772 CallOpc = PPCISD::CALL_NOP;
4776 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4777 InFlag = Chain.getValue(1);
4779 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4780 DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4783 InFlag = Chain.getValue(1);
4785 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4786 Ins, dl, DAG, InVals);
4790 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4791 SmallVectorImpl<SDValue> &InVals) const {
4792 SelectionDAG &DAG = CLI.DAG;
4794 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4795 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
4796 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
4797 SDValue Chain = CLI.Chain;
4798 SDValue Callee = CLI.Callee;
4799 bool &isTailCall = CLI.IsTailCall;
4800 CallingConv::ID CallConv = CLI.CallConv;
4801 bool isVarArg = CLI.IsVarArg;
4802 bool isPatchPoint = CLI.IsPatchPoint;
4803 ImmutableCallSite *CS = CLI.CS;
4806 if (Subtarget.useLongCalls() && !(CS && CS->isMustTailCall()))
4808 else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
4810 IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
4811 isVarArg, Outs, Ins, DAG);
4813 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4817 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4820 assert(isa<GlobalAddressSDNode>(Callee) &&
4821 "Callee should be an llvm::Function object.");
4823 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
4824 const unsigned Width = 80 - strlen("TCO caller: ")
4825 - strlen(", callee linkage: 0, 0");
4826 dbgs() << "TCO caller: "
4827 << left_justify(DAG.getMachineFunction().getName(), Width)
4828 << ", callee linkage: "
4829 << GV->getVisibility() << ", " << GV->getLinkage() << "\n"
4834 if (!isTailCall && CS && CS->isMustTailCall())
4835 report_fatal_error("failed to perform tail call elimination on a call "
4836 "site marked musttail");
4838 // When long calls (i.e. indirect calls) are always used, calls are always
4839 // made via function pointer. If we have a function name, first translate it
4841 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
4843 Callee = LowerGlobalAddress(Callee, DAG);
4845 if (Subtarget.isSVR4ABI()) {
4846 if (Subtarget.isPPC64())
4847 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4848 isTailCall, isPatchPoint, Outs, OutVals, Ins,
4849 dl, DAG, InVals, CS);
4851 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4852 isTailCall, isPatchPoint, Outs, OutVals, Ins,
4853 dl, DAG, InVals, CS);
4856 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4857 isTailCall, isPatchPoint, Outs, OutVals, Ins,
4858 dl, DAG, InVals, CS);
4861 SDValue PPCTargetLowering::LowerCall_32SVR4(
4862 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4863 bool isTailCall, bool isPatchPoint,
4864 const SmallVectorImpl<ISD::OutputArg> &Outs,
4865 const SmallVectorImpl<SDValue> &OutVals,
4866 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4867 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4868 ImmutableCallSite *CS) const {
4869 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4870 // of the 32-bit SVR4 ABI stack frame layout.
4872 assert((CallConv == CallingConv::C ||
4873 CallConv == CallingConv::Fast) && "Unknown calling convention!");
4875 unsigned PtrByteSize = 4;
4877 MachineFunction &MF = DAG.getMachineFunction();
4879 // Mark this function as potentially containing a function that contains a
4880 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4881 // and restoring the callers stack pointer in this functions epilog. This is
4882 // done because by tail calling the called function might overwrite the value
4883 // in this function's (MF) stack pointer stack slot 0(SP).
4884 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4885 CallConv == CallingConv::Fast)
4886 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4888 // Count how many bytes are to be pushed on the stack, including the linkage
4889 // area, parameter list area and the part of the local variable space which
4890 // contains copies of aggregates which are passed by value.
4892 // Assign locations to all of the outgoing arguments.
4893 SmallVector<CCValAssign, 16> ArgLocs;
4894 PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
4896 // Reserve space for the linkage area on the stack.
4897 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4900 CCInfo.PreAnalyzeCallOperands(Outs);
4903 // Handle fixed and variable vector arguments differently.
4904 // Fixed vector arguments go into registers as long as registers are
4905 // available. Variable vector arguments always go into memory.
4906 unsigned NumArgs = Outs.size();
4908 for (unsigned i = 0; i != NumArgs; ++i) {
4909 MVT ArgVT = Outs[i].VT;
4910 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4913 if (Outs[i].IsFixed) {
4914 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4917 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4923 errs() << "Call operand #" << i << " has unhandled type "
4924 << EVT(ArgVT).getEVTString() << "\n";
4926 llvm_unreachable(nullptr);
4930 // All arguments are treated the same.
4931 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4933 CCInfo.clearWasPPCF128();
4935 // Assign locations to all of the outgoing aggregate by value arguments.
4936 SmallVector<CCValAssign, 16> ByValArgLocs;
4937 CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
4939 // Reserve stack space for the allocations in CCInfo.
4940 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4942 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4944 // Size of the linkage area, parameter list area and the part of the local
4945 // space variable where copies of aggregates which are passed by value are
4947 unsigned NumBytes = CCByValInfo.getNextStackOffset();
4949 // Calculate by how many bytes the stack has to be adjusted in case of tail
4950 // call optimization.
4951 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4953 // Adjust the stack pointer for the new arguments...
4954 // These operations are automatically eliminated by the prolog/epilog pass
4955 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
4956 SDValue CallSeqStart = Chain;
4958 // Load the return address and frame pointer so it can be moved somewhere else
4961 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
4963 // Set up a copy of the stack pointer for use loading and storing any
4964 // arguments that may not fit in the registers available for argument
4966 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4968 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4969 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4970 SmallVector<SDValue, 8> MemOpChains;
4972 bool seenFloatArg = false;
4973 // Walk the register/memloc assignments, inserting copies/loads.
4974 for (unsigned i = 0, j = 0, e = ArgLocs.size();
4977 CCValAssign &VA = ArgLocs[i];
4978 SDValue Arg = OutVals[i];
4979 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4981 if (Flags.isByVal()) {
4982 // Argument is an aggregate which is passed by value, thus we need to
4983 // create a copy of it in the local variable space of the current stack
4984 // frame (which is the stack frame of the caller) and pass the address of
4985 // this copy to the callee.
4986 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4987 CCValAssign &ByValVA = ByValArgLocs[j++];
4988 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4990 // Memory reserved in the local variable space of the callers stack frame.
4991 unsigned LocMemOffset = ByValVA.getLocMemOffset();
4993 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
4994 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
4997 // Create a copy of the argument in the local area of the current
4999 SDValue MemcpyCall =
5000 CreateCopyOfByValArgument(Arg, PtrOff,
5001 CallSeqStart.getNode()->getOperand(0),
5004 // This must go outside the CALLSEQ_START..END.
5005 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5007 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5008 NewCallSeqStart.getNode());
5009 Chain = CallSeqStart = NewCallSeqStart;
5011 // Pass the address of the aggregate copy on the stack either in a
5012 // physical register or in the parameter list area of the current stack
5013 // frame to the callee.
5017 if (VA.isRegLoc()) {
5018 if (Arg.getValueType() == MVT::i1)
5019 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
5021 seenFloatArg |= VA.getLocVT().isFloatingPoint();
5022 // Put argument in a physical register.
5023 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5025 // Put argument in the parameter list area of the current stack frame.
5026 assert(VA.isMemLoc());
5027 unsigned LocMemOffset = VA.getLocMemOffset();
5030 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5031 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5034 MemOpChains.push_back(
5035 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5037 // Calculate and remember argument location.
5038 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5044 if (!MemOpChains.empty())
5045 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5047 // Build a sequence of copy-to-reg nodes chained together with token chain
5048 // and flag operands which copy the outgoing args into the appropriate regs.
5050 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5051 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5052 RegsToPass[i].second, InFlag);
5053 InFlag = Chain.getValue(1);
5056 // Set CR bit 6 to true if this is a vararg call with floating args passed in
5059 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5060 SDValue Ops[] = { Chain, InFlag };
5062 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5063 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5065 InFlag = Chain.getValue(1);
5069 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5072 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5073 /* unused except on PPC64 ELFv1 */ false, DAG,
5074 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5075 NumBytes, Ins, InVals, CS);
5078 // Copy an argument into memory, being careful to do this outside the
5079 // call sequence for the call to which the argument belongs.
5080 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5081 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5082 SelectionDAG &DAG, const SDLoc &dl) const {
5083 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5084 CallSeqStart.getNode()->getOperand(0),
5086 // The MEMCPY must go outside the CALLSEQ_START..END.
5087 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5088 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5090 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5091 NewCallSeqStart.getNode());
5092 return NewCallSeqStart;
5095 SDValue PPCTargetLowering::LowerCall_64SVR4(
5096 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5097 bool isTailCall, bool isPatchPoint,
5098 const SmallVectorImpl<ISD::OutputArg> &Outs,
5099 const SmallVectorImpl<SDValue> &OutVals,
5100 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5101 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5102 ImmutableCallSite *CS) const {
5103 bool isELFv2ABI = Subtarget.isELFv2ABI();
5104 bool isLittleEndian = Subtarget.isLittleEndian();
5105 unsigned NumOps = Outs.size();
5106 bool hasNest = false;
5107 bool IsSibCall = false;
5109 EVT PtrVT = getPointerTy(DAG.getDataLayout());
5110 unsigned PtrByteSize = 8;
5112 MachineFunction &MF = DAG.getMachineFunction();
5114 if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5117 // Mark this function as potentially containing a function that contains a
5118 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5119 // and restoring the callers stack pointer in this functions epilog. This is
5120 // done because by tail calling the called function might overwrite the value
5121 // in this function's (MF) stack pointer stack slot 0(SP).
5122 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5123 CallConv == CallingConv::Fast)
5124 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5126 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5127 "fastcc not supported on varargs functions");
5129 // Count how many bytes are to be pushed on the stack, including the linkage
5130 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
5131 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5132 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5133 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5134 unsigned NumBytes = LinkageSize;
5135 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5136 unsigned &QFPR_idx = FPR_idx;
5138 static const MCPhysReg GPR[] = {
5139 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5140 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5142 static const MCPhysReg VR[] = {
5143 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5144 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5147 const unsigned NumGPRs = array_lengthof(GPR);
5148 const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5149 const unsigned NumVRs = array_lengthof(VR);
5150 const unsigned NumQFPRs = NumFPRs;
5152 // On ELFv2, we can avoid allocating the parameter area if all the arguments
5153 // can be passed to the callee in registers.
5154 // For the fast calling convention, there is another check below.
5155 // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5156 bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5157 if (!HasParameterArea) {
5158 unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5159 unsigned AvailableFPRs = NumFPRs;
5160 unsigned AvailableVRs = NumVRs;
5161 unsigned NumBytesTmp = NumBytes;
5162 for (unsigned i = 0; i != NumOps; ++i) {
5163 if (Outs[i].Flags.isNest()) continue;
5164 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5165 PtrByteSize, LinkageSize, ParamAreaSize,
5166 NumBytesTmp, AvailableFPRs, AvailableVRs,
5167 Subtarget.hasQPX()))
5168 HasParameterArea = true;
5172 // When using the fast calling convention, we don't provide backing for
5173 // arguments that will be in registers.
5174 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5176 // Add up all the space actually used.
5177 for (unsigned i = 0; i != NumOps; ++i) {
5178 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5179 EVT ArgVT = Outs[i].VT;
5180 EVT OrigVT = Outs[i].ArgVT;
5185 if (CallConv == CallingConv::Fast) {
5186 if (Flags.isByVal())
5187 NumGPRsUsed += (Flags.getByValSize()+7)/8;
5189 switch (ArgVT.getSimpleVT().SimpleTy) {
5190 default: llvm_unreachable("Unexpected ValueType for argument!");
5194 if (++NumGPRsUsed <= NumGPRs)
5203 if (++NumVRsUsed <= NumVRs)
5207 // When using QPX, this is handled like a FP register, otherwise, it
5208 // is an Altivec register.
5209 if (Subtarget.hasQPX()) {
5210 if (++NumFPRsUsed <= NumFPRs)
5213 if (++NumVRsUsed <= NumVRs)
5219 case MVT::v4f64: // QPX
5220 case MVT::v4i1: // QPX
5221 if (++NumFPRsUsed <= NumFPRs)
5227 /* Respect alignment of argument on the stack. */
5229 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5230 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5232 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5233 if (Flags.isInConsecutiveRegsLast())
5234 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5237 unsigned NumBytesActuallyUsed = NumBytes;
5239 // In the old ELFv1 ABI,
5240 // the prolog code of the callee may store up to 8 GPR argument registers to
5241 // the stack, allowing va_start to index over them in memory if its varargs.
5242 // Because we cannot tell if this is needed on the caller side, we have to
5243 // conservatively assume that it is needed. As such, make sure we have at
5244 // least enough stack space for the caller to store the 8 GPRs.
5245 // In the ELFv2 ABI, we allocate the parameter area iff a callee
5246 // really requires memory operands, e.g. a vararg function.
5247 if (HasParameterArea)
5248 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5250 NumBytes = LinkageSize;
5252 // Tail call needs the stack to be aligned.
5253 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5254 CallConv == CallingConv::Fast)
5255 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5259 // Calculate by how many bytes the stack has to be adjusted in case of tail
5260 // call optimization.
5262 SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5264 // To protect arguments on the stack from being clobbered in a tail call,
5265 // force all the loads to happen before doing any other lowering.
5267 Chain = DAG.getStackArgumentTokenFactor(Chain);
5269 // Adjust the stack pointer for the new arguments...
5270 // These operations are automatically eliminated by the prolog/epilog pass
5272 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5273 SDValue CallSeqStart = Chain;
5275 // Load the return address and frame pointer so it can be move somewhere else
5278 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5280 // Set up a copy of the stack pointer for use loading and storing any
5281 // arguments that may not fit in the registers available for argument
5283 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5285 // Figure out which arguments are going to go in registers, and which in
5286 // memory. Also, if this is a vararg function, floating point operations
5287 // must be stored to our stack, and loaded into integer regs as well, if
5288 // any integer regs are available for argument passing.
5289 unsigned ArgOffset = LinkageSize;
5291 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5292 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5294 SmallVector<SDValue, 8> MemOpChains;
5295 for (unsigned i = 0; i != NumOps; ++i) {
5296 SDValue Arg = OutVals[i];
5297 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5298 EVT ArgVT = Outs[i].VT;
5299 EVT OrigVT = Outs[i].ArgVT;
5301 // PtrOff will be used to store the current argument to the stack if a
5302 // register cannot be found for it.
5305 // We re-align the argument offset for each argument, except when using the
5306 // fast calling convention, when we need to make sure we do that only when
5307 // we'll actually use a stack slot.
5308 auto ComputePtrOff = [&]() {
5309 /* Respect alignment of argument on the stack. */
5311 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5312 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5314 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5316 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5319 if (CallConv != CallingConv::Fast) {
5322 /* Compute GPR index associated with argument offset. */
5323 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5324 GPR_idx = std::min(GPR_idx, NumGPRs);
5327 // Promote integers to 64-bit values.
5328 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5329 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5330 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5331 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5334 // FIXME memcpy is used way more than necessary. Correctness first.
5335 // Note: "by value" is code for passing a structure by value, not
5337 if (Flags.isByVal()) {
5338 // Note: Size includes alignment padding, so
5339 // struct x { short a; char b; }
5340 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
5341 // These are the proper values we need for right-justifying the
5342 // aggregate in a parameter register.
5343 unsigned Size = Flags.getByValSize();
5345 // An empty aggregate parameter takes up no storage and no
5350 if (CallConv == CallingConv::Fast)
5353 // All aggregates smaller than 8 bytes must be passed right-justified.
5354 if (Size==1 || Size==2 || Size==4) {
5355 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5356 if (GPR_idx != NumGPRs) {
5357 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5358 MachinePointerInfo(), VT);
5359 MemOpChains.push_back(Load.getValue(1));
5360 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5362 ArgOffset += PtrByteSize;
5367 if (GPR_idx == NumGPRs && Size < 8) {
5368 SDValue AddPtr = PtrOff;
5369 if (!isLittleEndian) {
5370 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5371 PtrOff.getValueType());
5372 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5374 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5377 ArgOffset += PtrByteSize;
5380 // Copy entire object into memory. There are cases where gcc-generated
5381 // code assumes it is there, even if it could be put entirely into
5382 // registers. (This is not what the doc says.)
5384 // FIXME: The above statement is likely due to a misunderstanding of the
5385 // documents. All arguments must be copied into the parameter area BY
5386 // THE CALLEE in the event that the callee takes the address of any
5387 // formal argument. That has not yet been implemented. However, it is
5388 // reasonable to use the stack area as a staging area for the register
5391 // Skip this for small aggregates, as we will use the same slot for a
5392 // right-justified copy, below.
5394 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5398 // When a register is available, pass a small aggregate right-justified.
5399 if (Size < 8 && GPR_idx != NumGPRs) {
5400 // The easiest way to get this right-justified in a register
5401 // is to copy the structure into the rightmost portion of a
5402 // local variable slot, then load the whole slot into the
5404 // FIXME: The memcpy seems to produce pretty awful code for
5405 // small aggregates, particularly for packed ones.
5406 // FIXME: It would be preferable to use the slot in the
5407 // parameter save area instead of a new local variable.
5408 SDValue AddPtr = PtrOff;
5409 if (!isLittleEndian) {
5410 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5411 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5413 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5417 // Load the slot into the register.
5419 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5420 MemOpChains.push_back(Load.getValue(1));
5421 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5423 // Done with this argument.
5424 ArgOffset += PtrByteSize;
5428 // For aggregates larger than PtrByteSize, copy the pieces of the
5429 // object that fit into registers from the parameter save area.
5430 for (unsigned j=0; j<Size; j+=PtrByteSize) {
5431 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5432 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5433 if (GPR_idx != NumGPRs) {
5435 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5436 MemOpChains.push_back(Load.getValue(1));
5437 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5438 ArgOffset += PtrByteSize;
5440 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5447 switch (Arg.getSimpleValueType().SimpleTy) {
5448 default: llvm_unreachable("Unexpected ValueType for argument!");
5452 if (Flags.isNest()) {
5453 // The 'nest' parameter, if any, is passed in R11.
5454 RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5459 // These can be scalar arguments or elements of an integer array type
5460 // passed directly. Clang may use those instead of "byval" aggregate
5461 // types to avoid forcing arguments to memory unnecessarily.
5462 if (GPR_idx != NumGPRs) {
5463 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5465 if (CallConv == CallingConv::Fast)
5468 assert(HasParameterArea &&
5469 "Parameter area must exist to pass an argument in memory.");
5470 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5471 true, isTailCall, false, MemOpChains,
5472 TailCallArguments, dl);
5473 if (CallConv == CallingConv::Fast)
5474 ArgOffset += PtrByteSize;
5476 if (CallConv != CallingConv::Fast)
5477 ArgOffset += PtrByteSize;
5481 // These can be scalar arguments or elements of a float array type
5482 // passed directly. The latter are used to implement ELFv2 homogenous
5483 // float aggregates.
5485 // Named arguments go into FPRs first, and once they overflow, the
5486 // remaining arguments go into GPRs and then the parameter save area.
5487 // Unnamed arguments for vararg functions always go to GPRs and
5488 // then the parameter save area. For now, put all arguments to vararg
5489 // routines always in both locations (FPR *and* GPR or stack slot).
5490 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5491 bool NeededLoad = false;
5493 // First load the argument into the next available FPR.
5494 if (FPR_idx != NumFPRs)
5495 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5497 // Next, load the argument into GPR or stack slot if needed.
5498 if (!NeedGPROrStack)
5500 else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5501 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5502 // once we support fp <-> gpr moves.
5504 // In the non-vararg case, this can only ever happen in the
5505 // presence of f32 array types, since otherwise we never run
5506 // out of FPRs before running out of GPRs.
5509 // Double values are always passed in a single GPR.
5510 if (Arg.getValueType() != MVT::f32) {
5511 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5513 // Non-array float values are extended and passed in a GPR.
5514 } else if (!Flags.isInConsecutiveRegs()) {
5515 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5516 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5518 // If we have an array of floats, we collect every odd element
5519 // together with its predecessor into one GPR.
5520 } else if (ArgOffset % PtrByteSize != 0) {
5522 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5523 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5524 if (!isLittleEndian)
5526 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5528 // The final element, if even, goes into the first half of a GPR.
5529 } else if (Flags.isInConsecutiveRegsLast()) {
5530 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5531 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5532 if (!isLittleEndian)
5533 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5534 DAG.getConstant(32, dl, MVT::i32));
5536 // Non-final even elements are skipped; they will be handled
5537 // together the with subsequent argument on the next go-around.
5541 if (ArgVal.getNode())
5542 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5544 if (CallConv == CallingConv::Fast)
5547 // Single-precision floating-point values are mapped to the
5548 // second (rightmost) word of the stack doubleword.
5549 if (Arg.getValueType() == MVT::f32 &&
5550 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5551 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5552 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
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);
5563 // When passing an array of floats, the array occupies consecutive
5564 // space in the argument area; only round up to the next doubleword
5565 // at the end of the array. Otherwise, each float takes 8 bytes.
5566 if (CallConv != CallingConv::Fast || NeededLoad) {
5567 ArgOffset += (Arg.getValueType() == MVT::f32 &&
5568 Flags.isInConsecutiveRegs()) ? 4 : 8;
5569 if (Flags.isInConsecutiveRegsLast())
5570 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5581 if (!Subtarget.hasQPX()) {
5582 // These can be scalar arguments or elements of a vector array type
5583 // passed directly. The latter are used to implement ELFv2 homogenous
5584 // vector aggregates.
5586 // For a varargs call, named arguments go into VRs or on the stack as
5587 // usual; unnamed arguments always go to the stack or the corresponding
5588 // GPRs when within range. For now, we always put the value in both
5589 // locations (or even all three).
5591 assert(HasParameterArea &&
5592 "Parameter area must exist if we have a varargs call.");
5593 // We could elide this store in the case where the object fits
5594 // entirely in R registers. Maybe later.
5596 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5597 MemOpChains.push_back(Store);
5598 if (VR_idx != NumVRs) {
5600 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5601 MemOpChains.push_back(Load.getValue(1));
5602 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5605 for (unsigned i=0; i<16; i+=PtrByteSize) {
5606 if (GPR_idx == NumGPRs)
5608 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5609 DAG.getConstant(i, dl, PtrVT));
5611 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5612 MemOpChains.push_back(Load.getValue(1));
5613 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5618 // Non-varargs Altivec params go into VRs or on the stack.
5619 if (VR_idx != NumVRs) {
5620 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5622 if (CallConv == CallingConv::Fast)
5625 assert(HasParameterArea &&
5626 "Parameter area must exist to pass an argument in memory.");
5627 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5628 true, isTailCall, true, MemOpChains,
5629 TailCallArguments, dl);
5630 if (CallConv == CallingConv::Fast)
5634 if (CallConv != CallingConv::Fast)
5639 assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5640 "Invalid QPX parameter type");
5645 bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5647 assert(HasParameterArea &&
5648 "Parameter area must exist if we have a varargs call.");
5649 // We could elide this store in the case where the object fits
5650 // entirely in R registers. Maybe later.
5652 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5653 MemOpChains.push_back(Store);
5654 if (QFPR_idx != NumQFPRs) {
5655 SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
5656 PtrOff, MachinePointerInfo());
5657 MemOpChains.push_back(Load.getValue(1));
5658 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5660 ArgOffset += (IsF32 ? 16 : 32);
5661 for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5662 if (GPR_idx == NumGPRs)
5664 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5665 DAG.getConstant(i, dl, PtrVT));
5667 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5668 MemOpChains.push_back(Load.getValue(1));
5669 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5674 // Non-varargs QPX params go into registers or on the stack.
5675 if (QFPR_idx != NumQFPRs) {
5676 RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5678 if (CallConv == CallingConv::Fast)
5681 assert(HasParameterArea &&
5682 "Parameter area must exist to pass an argument in memory.");
5683 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5684 true, isTailCall, true, MemOpChains,
5685 TailCallArguments, dl);
5686 if (CallConv == CallingConv::Fast)
5687 ArgOffset += (IsF32 ? 16 : 32);
5690 if (CallConv != CallingConv::Fast)
5691 ArgOffset += (IsF32 ? 16 : 32);
5697 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
5698 "mismatch in size of parameter area");
5699 (void)NumBytesActuallyUsed;
5701 if (!MemOpChains.empty())
5702 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5704 // Check if this is an indirect call (MTCTR/BCTRL).
5705 // See PrepareCall() for more information about calls through function
5706 // pointers in the 64-bit SVR4 ABI.
5707 if (!isTailCall && !isPatchPoint &&
5708 !isFunctionGlobalAddress(Callee) &&
5709 !isa<ExternalSymbolSDNode>(Callee)) {
5710 // Load r2 into a virtual register and store it to the TOC save area.
5711 setUsesTOCBasePtr(DAG);
5712 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5713 // TOC save area offset.
5714 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5715 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5716 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5717 Chain = DAG.getStore(
5718 Val.getValue(1), dl, Val, AddPtr,
5719 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
5720 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5721 // This does not mean the MTCTR instruction must use R12; it's easier
5722 // to model this as an extra parameter, so do that.
5723 if (isELFv2ABI && !isPatchPoint)
5724 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5727 // Build a sequence of copy-to-reg nodes chained together with token chain
5728 // and flag operands which copy the outgoing args into the appropriate regs.
5730 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5731 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5732 RegsToPass[i].second, InFlag);
5733 InFlag = Chain.getValue(1);
5736 if (isTailCall && !IsSibCall)
5737 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5740 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
5741 DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5742 SPDiff, NumBytes, Ins, InVals, CS);
5745 SDValue PPCTargetLowering::LowerCall_Darwin(
5746 SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5747 bool isTailCall, bool isPatchPoint,
5748 const SmallVectorImpl<ISD::OutputArg> &Outs,
5749 const SmallVectorImpl<SDValue> &OutVals,
5750 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5751 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5752 ImmutableCallSite *CS) const {
5753 unsigned NumOps = Outs.size();
5755 EVT PtrVT = getPointerTy(DAG.getDataLayout());
5756 bool isPPC64 = PtrVT == MVT::i64;
5757 unsigned PtrByteSize = isPPC64 ? 8 : 4;
5759 MachineFunction &MF = DAG.getMachineFunction();
5761 // Mark this function as potentially containing a function that contains a
5762 // tail call. As a consequence the frame pointer will be used for dynamicalloc
5763 // and restoring the callers stack pointer in this functions epilog. This is
5764 // done because by tail calling the called function might overwrite the value
5765 // in this function's (MF) stack pointer stack slot 0(SP).
5766 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5767 CallConv == CallingConv::Fast)
5768 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5770 // Count how many bytes are to be pushed on the stack, including the linkage
5771 // area, and parameter passing area. We start with 24/48 bytes, which is
5772 // prereserved space for [SP][CR][LR][3 x unused].
5773 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5774 unsigned NumBytes = LinkageSize;
5776 // Add up all the space actually used.
5777 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5778 // they all go in registers, but we must reserve stack space for them for
5779 // possible use by the caller. In varargs or 64-bit calls, parameters are
5780 // assigned stack space in order, with padding so Altivec parameters are
5782 unsigned nAltivecParamsAtEnd = 0;
5783 for (unsigned i = 0; i != NumOps; ++i) {
5784 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5785 EVT ArgVT = Outs[i].VT;
5786 // Varargs Altivec parameters are padded to a 16 byte boundary.
5787 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5788 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5789 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5790 if (!isVarArg && !isPPC64) {
5791 // Non-varargs Altivec parameters go after all the non-Altivec
5792 // parameters; handle those later so we know how much padding we need.
5793 nAltivecParamsAtEnd++;
5796 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5797 NumBytes = ((NumBytes+15)/16)*16;
5799 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5802 // Allow for Altivec parameters at the end, if needed.
5803 if (nAltivecParamsAtEnd) {
5804 NumBytes = ((NumBytes+15)/16)*16;
5805 NumBytes += 16*nAltivecParamsAtEnd;
5808 // The prolog code of the callee may store up to 8 GPR argument registers to
5809 // the stack, allowing va_start to index over them in memory if its varargs.
5810 // Because we cannot tell if this is needed on the caller side, we have to
5811 // conservatively assume that it is needed. As such, make sure we have at
5812 // least enough stack space for the caller to store the 8 GPRs.
5813 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5815 // Tail call needs the stack to be aligned.
5816 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5817 CallConv == CallingConv::Fast)
5818 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5820 // Calculate by how many bytes the stack has to be adjusted in case of tail
5821 // call optimization.
5822 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5824 // To protect arguments on the stack from being clobbered in a tail call,
5825 // force all the loads to happen before doing any other lowering.
5827 Chain = DAG.getStackArgumentTokenFactor(Chain);
5829 // Adjust the stack pointer for the new arguments...
5830 // These operations are automatically eliminated by the prolog/epilog pass
5831 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5832 SDValue CallSeqStart = Chain;
5834 // Load the return address and frame pointer so it can be move somewhere else
5837 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5839 // Set up a copy of the stack pointer for use loading and storing any
5840 // arguments that may not fit in the registers available for argument
5844 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5846 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5848 // Figure out which arguments are going to go in registers, and which in
5849 // memory. Also, if this is a vararg function, floating point operations
5850 // must be stored to our stack, and loaded into integer regs as well, if
5851 // any integer regs are available for argument passing.
5852 unsigned ArgOffset = LinkageSize;
5853 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5855 static const MCPhysReg GPR_32[] = { // 32-bit registers.
5856 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5857 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5859 static const MCPhysReg GPR_64[] = { // 64-bit registers.
5860 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5861 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5863 static const MCPhysReg VR[] = {
5864 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5865 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5867 const unsigned NumGPRs = array_lengthof(GPR_32);
5868 const unsigned NumFPRs = 13;
5869 const unsigned NumVRs = array_lengthof(VR);
5871 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5873 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5874 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5876 SmallVector<SDValue, 8> MemOpChains;
5877 for (unsigned i = 0; i != NumOps; ++i) {
5878 SDValue Arg = OutVals[i];
5879 ISD::ArgFlagsTy Flags = Outs[i].Flags;
5881 // PtrOff will be used to store the current argument to the stack if a
5882 // register cannot be found for it.
5885 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5887 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5889 // On PPC64, promote integers to 64-bit values.
5890 if (isPPC64 && Arg.getValueType() == MVT::i32) {
5891 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5892 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5893 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5896 // FIXME memcpy is used way more than necessary. Correctness first.
5897 // Note: "by value" is code for passing a structure by value, not
5899 if (Flags.isByVal()) {
5900 unsigned Size = Flags.getByValSize();
5901 // Very small objects are passed right-justified. Everything else is
5902 // passed left-justified.
5903 if (Size==1 || Size==2) {
5904 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5905 if (GPR_idx != NumGPRs) {
5906 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5907 MachinePointerInfo(), VT);
5908 MemOpChains.push_back(Load.getValue(1));
5909 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5911 ArgOffset += PtrByteSize;
5913 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5914 PtrOff.getValueType());
5915 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5916 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5919 ArgOffset += PtrByteSize;
5923 // Copy entire object into memory. There are cases where gcc-generated
5924 // code assumes it is there, even if it could be put entirely into
5925 // registers. (This is not what the doc says.)
5926 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5930 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5931 // copy the pieces of the object that fit into registers from the
5932 // parameter save area.
5933 for (unsigned j=0; j<Size; j+=PtrByteSize) {
5934 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5935 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5936 if (GPR_idx != NumGPRs) {
5938 DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5939 MemOpChains.push_back(Load.getValue(1));
5940 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5941 ArgOffset += PtrByteSize;
5943 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5950 switch (Arg.getSimpleValueType().SimpleTy) {
5951 default: llvm_unreachable("Unexpected ValueType for argument!");
5955 if (GPR_idx != NumGPRs) {
5956 if (Arg.getValueType() == MVT::i1)
5957 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5959 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5961 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5962 isPPC64, isTailCall, false, MemOpChains,
5963 TailCallArguments, dl);
5965 ArgOffset += PtrByteSize;
5969 if (FPR_idx != NumFPRs) {
5970 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5974 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5975 MemOpChains.push_back(Store);
5977 // Float varargs are always shadowed in available integer registers
5978 if (GPR_idx != NumGPRs) {
5980 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5981 MemOpChains.push_back(Load.getValue(1));
5982 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5984 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
5985 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5986 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5988 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
5989 MemOpChains.push_back(Load.getValue(1));
5990 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5993 // If we have any FPRs remaining, we may also have GPRs remaining.
5994 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
5996 if (GPR_idx != NumGPRs)
5998 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
5999 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
6003 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6004 isPPC64, isTailCall, false, MemOpChains,
6005 TailCallArguments, dl);
6009 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6016 // These go aligned on the stack, or in the corresponding R registers
6017 // when within range. The Darwin PPC ABI doc claims they also go in
6018 // V registers; in fact gcc does this only for arguments that are
6019 // prototyped, not for those that match the ... We do it for all
6020 // arguments, seems to work.
6021 while (ArgOffset % 16 !=0) {
6022 ArgOffset += PtrByteSize;
6023 if (GPR_idx != NumGPRs)
6026 // We could elide this store in the case where the object fits
6027 // entirely in R registers. Maybe later.
6028 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6029 DAG.getConstant(ArgOffset, dl, PtrVT));
6031 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6032 MemOpChains.push_back(Store);
6033 if (VR_idx != NumVRs) {
6035 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6036 MemOpChains.push_back(Load.getValue(1));
6037 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6040 for (unsigned i=0; i<16; i+=PtrByteSize) {
6041 if (GPR_idx == NumGPRs)
6043 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6044 DAG.getConstant(i, dl, PtrVT));
6046 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6047 MemOpChains.push_back(Load.getValue(1));
6048 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6053 // Non-varargs Altivec params generally go in registers, but have
6054 // stack space allocated at the end.
6055 if (VR_idx != NumVRs) {
6056 // Doesn't have GPR space allocated.
6057 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6058 } else if (nAltivecParamsAtEnd==0) {
6059 // We are emitting Altivec params in order.
6060 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6061 isPPC64, isTailCall, true, MemOpChains,
6062 TailCallArguments, dl);
6068 // If all Altivec parameters fit in registers, as they usually do,
6069 // they get stack space following the non-Altivec parameters. We
6070 // don't track this here because nobody below needs it.
6071 // If there are more Altivec parameters than fit in registers emit
6073 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6075 // Offset is aligned; skip 1st 12 params which go in V registers.
6076 ArgOffset = ((ArgOffset+15)/16)*16;
6078 for (unsigned i = 0; i != NumOps; ++i) {
6079 SDValue Arg = OutVals[i];
6080 EVT ArgType = Outs[i].VT;
6081 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6082 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6085 // We are emitting Altivec params in order.
6086 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6087 isPPC64, isTailCall, true, MemOpChains,
6088 TailCallArguments, dl);
6095 if (!MemOpChains.empty())
6096 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6098 // On Darwin, R12 must contain the address of an indirect callee. This does
6099 // not mean the MTCTR instruction must use R12; it's easier to model this as
6100 // an extra parameter, so do that.
6102 !isFunctionGlobalAddress(Callee) &&
6103 !isa<ExternalSymbolSDNode>(Callee) &&
6104 !isBLACompatibleAddress(Callee, DAG))
6105 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6106 PPC::R12), Callee));
6108 // Build a sequence of copy-to-reg nodes chained together with token chain
6109 // and flag operands which copy the outgoing args into the appropriate regs.
6111 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6112 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6113 RegsToPass[i].second, InFlag);
6114 InFlag = Chain.getValue(1);
6118 PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6121 return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6122 /* unused except on PPC64 ELFv1 */ false, DAG,
6123 RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6124 NumBytes, Ins, InVals, CS);
6128 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6129 MachineFunction &MF, bool isVarArg,
6130 const SmallVectorImpl<ISD::OutputArg> &Outs,
6131 LLVMContext &Context) const {
6132 SmallVector<CCValAssign, 16> RVLocs;
6133 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6134 return CCInfo.CheckReturn(Outs, RetCC_PPC);
6138 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6140 const SmallVectorImpl<ISD::OutputArg> &Outs,
6141 const SmallVectorImpl<SDValue> &OutVals,
6142 const SDLoc &dl, SelectionDAG &DAG) const {
6143 SmallVector<CCValAssign, 16> RVLocs;
6144 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6146 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
6149 SmallVector<SDValue, 4> RetOps(1, Chain);
6151 // Copy the result values into the output registers.
6152 for (unsigned i = 0; i != RVLocs.size(); ++i) {
6153 CCValAssign &VA = RVLocs[i];
6154 assert(VA.isRegLoc() && "Can only return in registers!");
6156 SDValue Arg = OutVals[i];
6158 switch (VA.getLocInfo()) {
6159 default: llvm_unreachable("Unknown loc info!");
6160 case CCValAssign::Full: break;
6161 case CCValAssign::AExt:
6162 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6164 case CCValAssign::ZExt:
6165 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6167 case CCValAssign::SExt:
6168 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6172 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6173 Flag = Chain.getValue(1);
6174 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6177 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6178 const MCPhysReg *I =
6179 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6183 if (PPC::G8RCRegClass.contains(*I))
6184 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6185 else if (PPC::F8RCRegClass.contains(*I))
6186 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6187 else if (PPC::CRRCRegClass.contains(*I))
6188 RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6189 else if (PPC::VRRCRegClass.contains(*I))
6190 RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6192 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6196 RetOps[0] = Chain; // Update chain.
6198 // Add the flag if we have it.
6200 RetOps.push_back(Flag);
6202 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6206 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6207 SelectionDAG &DAG) const {
6210 // Get the corect type for integers.
6211 EVT IntVT = Op.getValueType();
6214 SDValue Chain = Op.getOperand(0);
6215 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6216 // Build a DYNAREAOFFSET node.
6217 SDValue Ops[2] = {Chain, FPSIdx};
6218 SDVTList VTs = DAG.getVTList(IntVT);
6219 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6222 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6223 SelectionDAG &DAG) const {
6224 // When we pop the dynamic allocation we need to restore the SP link.
6227 // Get the corect type for pointers.
6228 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6230 // Construct the stack pointer operand.
6231 bool isPPC64 = Subtarget.isPPC64();
6232 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6233 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6235 // Get the operands for the STACKRESTORE.
6236 SDValue Chain = Op.getOperand(0);
6237 SDValue SaveSP = Op.getOperand(1);
6239 // Load the old link SP.
6240 SDValue LoadLinkSP =
6241 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6243 // Restore the stack pointer.
6244 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6246 // Store the old link SP.
6247 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6250 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6251 MachineFunction &MF = DAG.getMachineFunction();
6252 bool isPPC64 = Subtarget.isPPC64();
6253 EVT PtrVT = getPointerTy(MF.getDataLayout());
6255 // Get current frame pointer save index. The users of this index will be
6256 // primarily DYNALLOC instructions.
6257 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6258 int RASI = FI->getReturnAddrSaveIndex();
6260 // If the frame pointer save index hasn't been defined yet.
6262 // Find out what the fix offset of the frame pointer save area.
6263 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6264 // Allocate the frame index for frame pointer save area.
6265 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6267 FI->setReturnAddrSaveIndex(RASI);
6269 return DAG.getFrameIndex(RASI, PtrVT);
6273 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6274 MachineFunction &MF = DAG.getMachineFunction();
6275 bool isPPC64 = Subtarget.isPPC64();
6276 EVT PtrVT = getPointerTy(MF.getDataLayout());
6278 // Get current frame pointer save index. The users of this index will be
6279 // primarily DYNALLOC instructions.
6280 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6281 int FPSI = FI->getFramePointerSaveIndex();
6283 // If the frame pointer save index hasn't been defined yet.
6285 // Find out what the fix offset of the frame pointer save area.
6286 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6287 // Allocate the frame index for frame pointer save area.
6288 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6290 FI->setFramePointerSaveIndex(FPSI);
6292 return DAG.getFrameIndex(FPSI, PtrVT);
6295 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6296 SelectionDAG &DAG) const {
6298 SDValue Chain = Op.getOperand(0);
6299 SDValue Size = Op.getOperand(1);
6302 // Get the corect type for pointers.
6303 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6305 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6306 DAG.getConstant(0, dl, PtrVT), Size);
6307 // Construct a node for the frame pointer save index.
6308 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6309 // Build a DYNALLOC node.
6310 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6311 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6312 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6315 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6316 SelectionDAG &DAG) const {
6317 MachineFunction &MF = DAG.getMachineFunction();
6319 bool isPPC64 = Subtarget.isPPC64();
6320 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6322 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6323 return DAG.getFrameIndex(FI, PtrVT);
6326 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6327 SelectionDAG &DAG) const {
6329 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6330 DAG.getVTList(MVT::i32, MVT::Other),
6331 Op.getOperand(0), Op.getOperand(1));
6334 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6335 SelectionDAG &DAG) const {
6337 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6338 Op.getOperand(0), Op.getOperand(1));
6341 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6342 if (Op.getValueType().isVector())
6343 return LowerVectorLoad(Op, DAG);
6345 assert(Op.getValueType() == MVT::i1 &&
6346 "Custom lowering only for i1 loads");
6348 // First, load 8 bits into 32 bits, then truncate to 1 bit.
6351 LoadSDNode *LD = cast<LoadSDNode>(Op);
6353 SDValue Chain = LD->getChain();
6354 SDValue BasePtr = LD->getBasePtr();
6355 MachineMemOperand *MMO = LD->getMemOperand();
6358 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6359 BasePtr, MVT::i8, MMO);
6360 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6362 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6363 return DAG.getMergeValues(Ops, dl);
6366 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6367 if (Op.getOperand(1).getValueType().isVector())
6368 return LowerVectorStore(Op, DAG);
6370 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6371 "Custom lowering only for i1 stores");
6373 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6376 StoreSDNode *ST = cast<StoreSDNode>(Op);
6378 SDValue Chain = ST->getChain();
6379 SDValue BasePtr = ST->getBasePtr();
6380 SDValue Value = ST->getValue();
6381 MachineMemOperand *MMO = ST->getMemOperand();
6383 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6385 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6388 // FIXME: Remove this once the ANDI glue bug is fixed:
6389 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6390 assert(Op.getValueType() == MVT::i1 &&
6391 "Custom lowering only for i1 results");
6394 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6398 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6400 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6401 // Not FP? Not a fsel.
6402 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6403 !Op.getOperand(2).getValueType().isFloatingPoint())
6406 // We might be able to do better than this under some circumstances, but in
6407 // general, fsel-based lowering of select is a finite-math-only optimization.
6408 // For more information, see section F.3 of the 2.06 ISA specification.
6409 if (!DAG.getTarget().Options.NoInfsFPMath ||
6410 !DAG.getTarget().Options.NoNaNsFPMath)
6412 // TODO: Propagate flags from the select rather than global settings.
6414 Flags.setNoInfs(true);
6415 Flags.setNoNaNs(true);
6417 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6419 EVT ResVT = Op.getValueType();
6420 EVT CmpVT = Op.getOperand(0).getValueType();
6421 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6422 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
6425 // If the RHS of the comparison is a 0.0, we don't need to do the
6426 // subtraction at all.
6428 if (isFloatingPointZero(RHS))
6430 default: break; // SETUO etc aren't handled by fsel.
6434 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
6435 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6436 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6437 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
6438 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6439 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6440 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6443 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
6446 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
6447 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6448 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6451 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
6454 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
6455 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6456 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6457 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6462 default: break; // SETUO etc aren't handled by fsel.
6466 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6467 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6468 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6469 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6470 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
6471 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6472 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6473 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6476 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6477 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6478 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6479 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6482 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6483 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6484 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6485 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6488 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6489 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6490 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6491 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6494 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6495 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
6496 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6497 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6502 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6504 const SDLoc &dl) const {
6505 assert(Op.getOperand(0).getValueType().isFloatingPoint());
6506 SDValue Src = Op.getOperand(0);
6507 if (Src.getValueType() == MVT::f32)
6508 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6511 switch (Op.getSimpleValueType().SimpleTy) {
6512 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6515 Op.getOpcode() == ISD::FP_TO_SINT
6517 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6521 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6522 "i64 FP_TO_UINT is supported only with FPCVT");
6523 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6529 // Convert the FP value to an int value through memory.
6530 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6531 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6532 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6533 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6534 MachinePointerInfo MPI =
6535 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6537 // Emit a store to the stack slot.
6540 MachineFunction &MF = DAG.getMachineFunction();
6541 MachineMemOperand *MMO =
6542 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6543 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6544 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6545 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6547 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
6549 // Result is a load from the stack slot. If loading 4 bytes, make sure to
6550 // add in a bias on big endian.
6551 if (Op.getValueType() == MVT::i32 && !i32Stack) {
6552 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6553 DAG.getConstant(4, dl, FIPtr.getValueType()));
6554 MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6562 /// \brief Custom lowers floating point to integer conversions to use
6563 /// the direct move instructions available in ISA 2.07 to avoid the
6564 /// need for load/store combinations.
6565 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6567 const SDLoc &dl) const {
6568 assert(Op.getOperand(0).getValueType().isFloatingPoint());
6569 SDValue Src = Op.getOperand(0);
6571 if (Src.getValueType() == MVT::f32)
6572 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6575 switch (Op.getSimpleValueType().SimpleTy) {
6576 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6579 Op.getOpcode() == ISD::FP_TO_SINT
6581 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6583 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6586 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6587 "i64 FP_TO_UINT is supported only with FPCVT");
6588 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6591 Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6597 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6598 const SDLoc &dl) const {
6599 if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6600 return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6603 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6605 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6606 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6609 // We're trying to insert a regular store, S, and then a load, L. If the
6610 // incoming value, O, is a load, we might just be able to have our load use the
6611 // address used by O. However, we don't know if anything else will store to
6612 // that address before we can load from it. To prevent this situation, we need
6613 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6614 // the same chain operand as O, we create a token factor from the chain results
6615 // of O and L, and we replace all uses of O's chain result with that token
6616 // factor (see spliceIntoChain below for this last part).
6617 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6620 ISD::LoadExtType ET) const {
6622 if (ET == ISD::NON_EXTLOAD &&
6623 (Op.getOpcode() == ISD::FP_TO_UINT ||
6624 Op.getOpcode() == ISD::FP_TO_SINT) &&
6625 isOperationLegalOrCustom(Op.getOpcode(),
6626 Op.getOperand(0).getValueType())) {
6628 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6632 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6633 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6634 LD->isNonTemporal())
6636 if (LD->getMemoryVT() != MemVT)
6639 RLI.Ptr = LD->getBasePtr();
6640 if (LD->isIndexed() && !LD->getOffset().isUndef()) {
6641 assert(LD->getAddressingMode() == ISD::PRE_INC &&
6642 "Non-pre-inc AM on PPC?");
6643 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6647 RLI.Chain = LD->getChain();
6648 RLI.MPI = LD->getPointerInfo();
6649 RLI.IsDereferenceable = LD->isDereferenceable();
6650 RLI.IsInvariant = LD->isInvariant();
6651 RLI.Alignment = LD->getAlignment();
6652 RLI.AAInfo = LD->getAAInfo();
6653 RLI.Ranges = LD->getRanges();
6655 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6659 // Given the head of the old chain, ResChain, insert a token factor containing
6660 // it and NewResChain, and make users of ResChain now be users of that token
6662 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6663 SDValue NewResChain,
6664 SelectionDAG &DAG) const {
6668 SDLoc dl(NewResChain);
6670 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6671 NewResChain, DAG.getUNDEF(MVT::Other));
6672 assert(TF.getNode() != NewResChain.getNode() &&
6673 "A new TF really is required here");
6675 DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6676 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6679 /// \brief Analyze profitability of direct move
6680 /// prefer float load to int load plus direct move
6681 /// when there is no integer use of int load
6682 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
6683 SDNode *Origin = Op.getOperand(0).getNode();
6684 if (Origin->getOpcode() != ISD::LOAD)
6687 // If there is no LXSIBZX/LXSIHZX, like Power8,
6688 // prefer direct move if the memory size is 1 or 2 bytes.
6689 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
6690 if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
6693 for (SDNode::use_iterator UI = Origin->use_begin(),
6694 UE = Origin->use_end();
6697 // Only look at the users of the loaded value.
6698 if (UI.getUse().get().getResNo() != 0)
6701 if (UI->getOpcode() != ISD::SINT_TO_FP &&
6702 UI->getOpcode() != ISD::UINT_TO_FP)
6709 /// \brief Custom lowers integer to floating point conversions to use
6710 /// the direct move instructions available in ISA 2.07 to avoid the
6711 /// need for load/store combinations.
6712 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6714 const SDLoc &dl) const {
6715 assert((Op.getValueType() == MVT::f32 ||
6716 Op.getValueType() == MVT::f64) &&
6717 "Invalid floating point type as target of conversion");
6718 assert(Subtarget.hasFPCVT() &&
6719 "Int to FP conversions with direct moves require FPCVT");
6721 SDValue Src = Op.getOperand(0);
6722 bool SinglePrec = Op.getValueType() == MVT::f32;
6723 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6724 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6725 unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6726 (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6729 FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6731 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6734 FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6735 FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6741 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6742 SelectionDAG &DAG) const {
6745 if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6746 if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6749 SDValue Value = Op.getOperand(0);
6750 // The values are now known to be -1 (false) or 1 (true). To convert this
6751 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6752 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6753 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6755 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
6757 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6759 if (Op.getValueType() != MVT::v4f64)
6760 Value = DAG.getNode(ISD::FP_ROUND, dl,
6761 Op.getValueType(), Value,
6762 DAG.getIntPtrConstant(1, dl));
6766 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6767 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6770 if (Op.getOperand(0).getValueType() == MVT::i1)
6771 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6772 DAG.getConstantFP(1.0, dl, Op.getValueType()),
6773 DAG.getConstantFP(0.0, dl, Op.getValueType()));
6775 // If we have direct moves, we can do all the conversion, skip the store/load
6776 // however, without FPCVT we can't do most conversions.
6777 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
6778 Subtarget.isPPC64() && Subtarget.hasFPCVT())
6779 return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6781 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6782 "UINT_TO_FP is supported only with FPCVT");
6784 // If we have FCFIDS, then use it when converting to single-precision.
6785 // Otherwise, convert to double-precision and then round.
6786 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6787 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6789 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6791 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6795 if (Op.getOperand(0).getValueType() == MVT::i64) {
6796 SDValue SINT = Op.getOperand(0);
6797 // When converting to single-precision, we actually need to convert
6798 // to double-precision first and then round to single-precision.
6799 // To avoid double-rounding effects during that operation, we have
6800 // to prepare the input operand. Bits that might be truncated when
6801 // converting to double-precision are replaced by a bit that won't
6802 // be lost at this stage, but is below the single-precision rounding
6805 // However, if -enable-unsafe-fp-math is in effect, accept double
6806 // rounding to avoid the extra overhead.
6807 if (Op.getValueType() == MVT::f32 &&
6808 !Subtarget.hasFPCVT() &&
6809 !DAG.getTarget().Options.UnsafeFPMath) {
6811 // Twiddle input to make sure the low 11 bits are zero. (If this
6812 // is the case, we are guaranteed the value will fit into the 53 bit
6813 // mantissa of an IEEE double-precision value without rounding.)
6814 // If any of those low 11 bits were not zero originally, make sure
6815 // bit 12 (value 2048) is set instead, so that the final rounding
6816 // to single-precision gets the correct result.
6817 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6818 SINT, DAG.getConstant(2047, dl, MVT::i64));
6819 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6820 Round, DAG.getConstant(2047, dl, MVT::i64));
6821 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6822 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6823 Round, DAG.getConstant(-2048, dl, MVT::i64));
6825 // However, we cannot use that value unconditionally: if the magnitude
6826 // of the input value is small, the bit-twiddling we did above might
6827 // end up visibly changing the output. Fortunately, in that case, we
6828 // don't need to twiddle bits since the original input will convert
6829 // exactly to double-precision floating-point already. Therefore,
6830 // construct a conditional to use the original value if the top 11
6831 // bits are all sign-bit copies, and use the rounded value computed
6833 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6834 SINT, DAG.getConstant(53, dl, MVT::i32));
6835 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6836 Cond, DAG.getConstant(1, dl, MVT::i64));
6837 Cond = DAG.getSetCC(dl, MVT::i32,
6838 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6840 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6846 MachineFunction &MF = DAG.getMachineFunction();
6847 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6848 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6849 RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6850 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6851 } else if (Subtarget.hasLFIWAX() &&
6852 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6853 MachineMemOperand *MMO =
6854 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6855 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6856 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6857 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6858 DAG.getVTList(MVT::f64, MVT::Other),
6859 Ops, MVT::i32, MMO);
6860 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6861 } else if (Subtarget.hasFPCVT() &&
6862 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6863 MachineMemOperand *MMO =
6864 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6865 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6866 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6867 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6868 DAG.getVTList(MVT::f64, MVT::Other),
6869 Ops, MVT::i32, MMO);
6870 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6871 } else if (((Subtarget.hasLFIWAX() &&
6872 SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6873 (Subtarget.hasFPCVT() &&
6874 SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6875 SINT.getOperand(0).getValueType() == MVT::i32) {
6876 MachineFrameInfo &MFI = MF.getFrameInfo();
6877 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6879 int FrameIdx = MFI.CreateStackObject(4, 4, false);
6880 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6883 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6884 MachinePointerInfo::getFixedStack(
6885 DAG.getMachineFunction(), FrameIdx));
6887 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6888 "Expected an i32 store");
6893 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6896 MachineMemOperand *MMO =
6897 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6898 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6899 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6900 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6901 PPCISD::LFIWZX : PPCISD::LFIWAX,
6902 dl, DAG.getVTList(MVT::f64, MVT::Other),
6903 Ops, MVT::i32, MMO);
6905 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6907 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6909 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6910 FP = DAG.getNode(ISD::FP_ROUND, dl,
6911 MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6915 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6916 "Unhandled INT_TO_FP type in custom expander!");
6917 // Since we only generate this in 64-bit mode, we can take advantage of
6918 // 64-bit registers. In particular, sign extend the input value into the
6919 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6920 // then lfd it and fcfid it.
6921 MachineFunction &MF = DAG.getMachineFunction();
6922 MachineFrameInfo &MFI = MF.getFrameInfo();
6923 EVT PtrVT = getPointerTy(MF.getDataLayout());
6926 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6929 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6931 int FrameIdx = MFI.CreateStackObject(4, 4, false);
6932 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6935 DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6936 MachinePointerInfo::getFixedStack(
6937 DAG.getMachineFunction(), FrameIdx));
6939 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6940 "Expected an i32 store");
6945 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6949 MachineMemOperand *MMO =
6950 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6951 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6952 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6953 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6954 PPCISD::LFIWZX : PPCISD::LFIWAX,
6955 dl, DAG.getVTList(MVT::f64, MVT::Other),
6956 Ops, MVT::i32, MMO);
6958 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6960 assert(Subtarget.isPPC64() &&
6961 "i32->FP without LFIWAX supported only on PPC64");
6963 int FrameIdx = MFI.CreateStackObject(8, 8, false);
6964 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6966 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6969 // STD the extended value into the stack slot.
6970 SDValue Store = DAG.getStore(
6971 DAG.getEntryNode(), dl, Ext64, FIdx,
6972 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6974 // Load the value as a double.
6976 MVT::f64, dl, Store, FIdx,
6977 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6980 // FCFID it and return it.
6981 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
6982 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6983 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
6984 DAG.getIntPtrConstant(0, dl));
6988 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6989 SelectionDAG &DAG) const {
6992 The rounding mode is in bits 30:31 of FPSR, and has the following
6999 FLT_ROUNDS, on the other hand, expects the following:
7006 To perform the conversion, we do:
7007 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7010 MachineFunction &MF = DAG.getMachineFunction();
7011 EVT VT = Op.getValueType();
7012 EVT PtrVT = getPointerTy(MF.getDataLayout());
7014 // Save FP Control Word to register
7016 MVT::f64, // return register
7017 MVT::Glue // unused in this context
7019 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7021 // Save FP register to stack slot
7022 int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7023 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7024 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7025 MachinePointerInfo());
7027 // Load FP Control Word from low 32 bits of stack slot.
7028 SDValue Four = DAG.getConstant(4, dl, PtrVT);
7029 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7030 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7032 // Transform as necessary
7034 DAG.getNode(ISD::AND, dl, MVT::i32,
7035 CWD, DAG.getConstant(3, dl, MVT::i32));
7037 DAG.getNode(ISD::SRL, dl, MVT::i32,
7038 DAG.getNode(ISD::AND, dl, MVT::i32,
7039 DAG.getNode(ISD::XOR, dl, MVT::i32,
7040 CWD, DAG.getConstant(3, dl, MVT::i32)),
7041 DAG.getConstant(3, dl, MVT::i32)),
7042 DAG.getConstant(1, dl, MVT::i32));
7045 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7047 return DAG.getNode((VT.getSizeInBits() < 16 ?
7048 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7051 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7052 EVT VT = Op.getValueType();
7053 unsigned BitWidth = VT.getSizeInBits();
7055 assert(Op.getNumOperands() == 3 &&
7056 VT == Op.getOperand(1).getValueType() &&
7059 // Expand into a bunch of logical ops. Note that these ops
7060 // depend on the PPC behavior for oversized shift amounts.
7061 SDValue Lo = Op.getOperand(0);
7062 SDValue Hi = Op.getOperand(1);
7063 SDValue Amt = Op.getOperand(2);
7064 EVT AmtVT = Amt.getValueType();
7066 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7067 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7068 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7069 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7070 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7071 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7072 DAG.getConstant(-BitWidth, dl, AmtVT));
7073 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7074 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7075 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7076 SDValue OutOps[] = { OutLo, OutHi };
7077 return DAG.getMergeValues(OutOps, dl);
7080 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7081 EVT VT = Op.getValueType();
7083 unsigned BitWidth = VT.getSizeInBits();
7084 assert(Op.getNumOperands() == 3 &&
7085 VT == Op.getOperand(1).getValueType() &&
7088 // Expand into a bunch of logical ops. Note that these ops
7089 // depend on the PPC behavior for oversized shift amounts.
7090 SDValue Lo = Op.getOperand(0);
7091 SDValue Hi = Op.getOperand(1);
7092 SDValue Amt = Op.getOperand(2);
7093 EVT AmtVT = Amt.getValueType();
7095 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7096 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7097 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7098 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7099 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7100 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7101 DAG.getConstant(-BitWidth, dl, AmtVT));
7102 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7103 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7104 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7105 SDValue OutOps[] = { OutLo, OutHi };
7106 return DAG.getMergeValues(OutOps, dl);
7109 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7111 EVT VT = Op.getValueType();
7112 unsigned BitWidth = VT.getSizeInBits();
7113 assert(Op.getNumOperands() == 3 &&
7114 VT == Op.getOperand(1).getValueType() &&
7117 // Expand into a bunch of logical ops, followed by a select_cc.
7118 SDValue Lo = Op.getOperand(0);
7119 SDValue Hi = Op.getOperand(1);
7120 SDValue Amt = Op.getOperand(2);
7121 EVT AmtVT = Amt.getValueType();
7123 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7124 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7125 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7126 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7127 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7128 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7129 DAG.getConstant(-BitWidth, dl, AmtVT));
7130 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7131 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7132 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7133 Tmp4, Tmp6, ISD::SETLE);
7134 SDValue OutOps[] = { OutLo, OutHi };
7135 return DAG.getMergeValues(OutOps, dl);
7138 //===----------------------------------------------------------------------===//
7139 // Vector related lowering.
7142 /// BuildSplatI - Build a canonical splati of Val with an element size of
7143 /// SplatSize. Cast the result to VT.
7144 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7145 SelectionDAG &DAG, const SDLoc &dl) {
7146 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7148 static const MVT VTys[] = { // canonical VT to use for each size.
7149 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7152 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7154 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7158 EVT CanonicalVT = VTys[SplatSize-1];
7160 // Build a canonical splat for this value.
7161 return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7164 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7165 /// specified intrinsic ID.
7166 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7167 const SDLoc &dl, EVT DestVT = MVT::Other) {
7168 if (DestVT == MVT::Other) DestVT = Op.getValueType();
7169 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7170 DAG.getConstant(IID, dl, MVT::i32), Op);
7173 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7174 /// specified intrinsic ID.
7175 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7176 SelectionDAG &DAG, const SDLoc &dl,
7177 EVT DestVT = MVT::Other) {
7178 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7179 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7180 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7183 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7184 /// specified intrinsic ID.
7185 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7186 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7187 EVT DestVT = MVT::Other) {
7188 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7189 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7190 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7193 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7194 /// amount. The result has the specified value type.
7195 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7196 SelectionDAG &DAG, const SDLoc &dl) {
7197 // Force LHS/RHS to be the right type.
7198 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7199 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7202 for (unsigned i = 0; i != 16; ++i)
7204 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7205 return DAG.getNode(ISD::BITCAST, dl, VT, T);
7208 /// Do we have an efficient pattern in a .td file for this node?
7210 /// \param V - pointer to the BuildVectorSDNode being matched
7211 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
7213 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
7214 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
7215 /// the opposite is true (expansion is beneficial) are:
7216 /// - The node builds a vector out of integers that are not 32 or 64-bits
7217 /// - The node builds a vector out of constants
7218 /// - The node is a "load-and-splat"
7219 /// In all other cases, we will choose to keep the BUILD_VECTOR.
7220 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
7221 bool HasDirectMove) {
7222 EVT VecVT = V->getValueType(0);
7223 bool RightType = VecVT == MVT::v2f64 || VecVT == MVT::v4f32 ||
7224 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
7228 bool IsSplat = true;
7229 bool IsLoad = false;
7230 SDValue Op0 = V->getOperand(0);
7232 // This function is called in a block that confirms the node is not a constant
7233 // splat. So a constant BUILD_VECTOR here means the vector is built out of
7234 // different constants.
7235 if (V->isConstant())
7237 for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
7238 if (V->getOperand(i).isUndef())
7240 // We want to expand nodes that represent load-and-splat even if the
7241 // loaded value is a floating point truncation or conversion to int.
7242 if (V->getOperand(i).getOpcode() == ISD::LOAD ||
7243 (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
7244 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7245 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
7246 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7247 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
7248 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
7250 // If the operands are different or the input is not a load and has more
7251 // uses than just this BV node, then it isn't a splat.
7252 if (V->getOperand(i) != Op0 ||
7253 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
7256 return !(IsSplat && IsLoad);
7259 // If this is a case we can't handle, return null and let the default
7260 // expansion code take care of it. If we CAN select this case, and if it
7261 // selects to a single instruction, return Op. Otherwise, if we can codegen
7262 // this case more efficiently than a constant pool load, lower it to the
7263 // sequence of ops that should be used.
7264 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7265 SelectionDAG &DAG) const {
7267 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7268 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7270 if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7271 // We first build an i32 vector, load it into a QPX register,
7272 // then convert it to a floating-point vector and compare it
7273 // to a zero vector to get the boolean result.
7274 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7275 int FrameIdx = MFI.CreateStackObject(16, 16, false);
7276 MachinePointerInfo PtrInfo =
7277 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7278 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7279 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7281 assert(BVN->getNumOperands() == 4 &&
7282 "BUILD_VECTOR for v4i1 does not have 4 operands");
7284 bool IsConst = true;
7285 for (unsigned i = 0; i < 4; ++i) {
7286 if (BVN->getOperand(i).isUndef()) continue;
7287 if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7295 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7297 ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7300 for (unsigned i = 0; i < 4; ++i) {
7301 if (BVN->getOperand(i).isUndef())
7302 CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7303 else if (isNullConstant(BVN->getOperand(i)))
7309 Constant *CP = ConstantVector::get(CV);
7310 SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7311 16 /* alignment */);
7313 SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7314 SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7315 return DAG.getMemIntrinsicNode(
7316 PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7317 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7320 SmallVector<SDValue, 4> Stores;
7321 for (unsigned i = 0; i < 4; ++i) {
7322 if (BVN->getOperand(i).isUndef()) continue;
7324 unsigned Offset = 4*i;
7325 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7326 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7328 unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7329 if (StoreSize > 4) {
7331 DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7332 PtrInfo.getWithOffset(Offset), MVT::i32));
7334 SDValue StoreValue = BVN->getOperand(i);
7336 StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7338 Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7339 PtrInfo.getWithOffset(Offset)));
7344 if (!Stores.empty())
7345 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7347 StoreChain = DAG.getEntryNode();
7349 // Now load from v4i32 into the QPX register; this will extend it to
7350 // v4i64 but not yet convert it to a floating point. Nevertheless, this
7351 // is typed as v4f64 because the QPX register integer states are not
7352 // explicitly represented.
7354 SDValue Ops[] = {StoreChain,
7355 DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7357 SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7359 SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7360 dl, VTs, Ops, MVT::v4i32, PtrInfo);
7361 LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7362 DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7365 SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7367 return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7370 // All other QPX vectors are handled by generic code.
7371 if (Subtarget.hasQPX())
7374 // Check if this is a splat of a constant value.
7375 APInt APSplatBits, APSplatUndef;
7376 unsigned SplatBitSize;
7378 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7379 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7380 SplatBitSize > 32) {
7381 // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
7382 // lowered to VSX instructions under certain conditions.
7383 // Without VSX, there is no pattern more efficient than expanding the node.
7384 if (Subtarget.hasVSX() &&
7385 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove()))
7390 unsigned SplatBits = APSplatBits.getZExtValue();
7391 unsigned SplatUndef = APSplatUndef.getZExtValue();
7392 unsigned SplatSize = SplatBitSize / 8;
7394 // First, handle single instruction cases.
7397 if (SplatBits == 0) {
7398 // Canonicalize all zero vectors to be v4i32.
7399 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7400 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7401 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7406 // We have XXSPLTIB for constant splats one byte wide
7407 if (Subtarget.hasP9Vector() && SplatSize == 1) {
7408 // This is a splat of 1-byte elements with some elements potentially undef.
7409 // Rather than trying to match undef in the SDAG patterns, ensure that all
7410 // elements are the same constant.
7411 if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
7412 SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
7414 SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
7415 if (Op.getValueType() != MVT::v16i8)
7416 return DAG.getBitcast(Op.getValueType(), NewBV);
7422 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7423 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7425 if (SextVal >= -16 && SextVal <= 15)
7426 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7428 // Two instruction sequences.
7430 // If this value is in the range [-32,30] and is even, use:
7431 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7432 // If this value is in the range [17,31] and is odd, use:
7433 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7434 // If this value is in the range [-31,-17] and is odd, use:
7435 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7436 // Note the last two are three-instruction sequences.
7437 if (SextVal >= -32 && SextVal <= 31) {
7438 // To avoid having these optimizations undone by constant folding,
7439 // we convert to a pseudo that will be expanded later into one of
7441 SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7442 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7443 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7444 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7445 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7446 if (VT == Op.getValueType())
7449 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7452 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
7453 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
7455 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7456 // Make -1 and vspltisw -1:
7457 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7459 // Make the VSLW intrinsic, computing 0x8000_0000.
7460 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7463 // xor by OnesV to invert it.
7464 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7465 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7468 // Check to see if this is a wide variety of vsplti*, binop self cases.
7469 static const signed char SplatCsts[] = {
7470 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7471 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7474 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7475 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7476 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
7477 int i = SplatCsts[idx];
7479 // Figure out what shift amount will be used by altivec if shifted by i in
7481 unsigned TypeShiftAmt = i & (SplatBitSize-1);
7483 // vsplti + shl self.
7484 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7485 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7486 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7487 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7488 Intrinsic::ppc_altivec_vslw
7490 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7491 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7494 // vsplti + srl self.
7495 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7496 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7497 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7498 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7499 Intrinsic::ppc_altivec_vsrw
7501 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7502 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7505 // vsplti + sra self.
7506 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7507 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7508 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7509 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7510 Intrinsic::ppc_altivec_vsraw
7512 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7513 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7516 // vsplti + rol self.
7517 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7518 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7519 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7520 static const unsigned IIDs[] = { // Intrinsic to use for each size.
7521 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7522 Intrinsic::ppc_altivec_vrlw
7524 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7525 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7528 // t = vsplti c, result = vsldoi t, t, 1
7529 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7530 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7531 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7532 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7534 // t = vsplti c, result = vsldoi t, t, 2
7535 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7536 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7537 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7538 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7540 // t = vsplti c, result = vsldoi t, t, 3
7541 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7542 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7543 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7544 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7551 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7552 /// the specified operations to build the shuffle.
7553 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7554 SDValue RHS, SelectionDAG &DAG,
7556 unsigned OpNum = (PFEntry >> 26) & 0x0F;
7557 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7558 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
7561 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7573 if (OpNum == OP_COPY) {
7574 if (LHSID == (1*9+2)*9+3) return LHS;
7575 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7579 SDValue OpLHS, OpRHS;
7580 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7581 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7585 default: llvm_unreachable("Unknown i32 permute!");
7587 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
7588 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7589 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
7590 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7593 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7594 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7595 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7596 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7599 for (unsigned i = 0; i != 16; ++i)
7600 ShufIdxs[i] = (i&3)+0;
7603 for (unsigned i = 0; i != 16; ++i)
7604 ShufIdxs[i] = (i&3)+4;
7607 for (unsigned i = 0; i != 16; ++i)
7608 ShufIdxs[i] = (i&3)+8;
7611 for (unsigned i = 0; i != 16; ++i)
7612 ShufIdxs[i] = (i&3)+12;
7615 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7617 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7619 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7621 EVT VT = OpLHS.getValueType();
7622 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7623 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7624 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7625 return DAG.getNode(ISD::BITCAST, dl, VT, T);
7628 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
7629 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
7630 /// return the code it can be lowered into. Worst case, it can always be
7631 /// lowered into a vperm.
7632 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7633 SelectionDAG &DAG) const {
7635 SDValue V1 = Op.getOperand(0);
7636 SDValue V2 = Op.getOperand(1);
7637 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7638 EVT VT = Op.getValueType();
7639 bool isLittleEndian = Subtarget.isLittleEndian();
7641 unsigned ShiftElts, InsertAtByte;
7643 if (Subtarget.hasP9Vector() &&
7644 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
7648 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7649 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
7651 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
7652 DAG.getConstant(ShiftElts, dl, MVT::i32));
7653 SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Shl,
7654 DAG.getConstant(InsertAtByte, dl, MVT::i32));
7655 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7657 SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Conv2,
7658 DAG.getConstant(InsertAtByte, dl, MVT::i32));
7659 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7662 if (Subtarget.hasVSX()) {
7663 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
7664 int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
7666 // If the source for the shuffle is a scalar_to_vector that came from a
7667 // 32-bit load, it will have used LXVWSX so we don't need to splat again.
7668 if (Subtarget.hasP9Vector() &&
7669 ((isLittleEndian && SplatIdx == 3) ||
7670 (!isLittleEndian && SplatIdx == 0))) {
7671 SDValue Src = V1.getOperand(0);
7672 if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7673 Src.getOperand(0).getOpcode() == ISD::LOAD &&
7674 Src.getOperand(0).hasOneUse())
7677 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7678 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
7679 DAG.getConstant(SplatIdx, dl, MVT::i32));
7680 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
7683 // Left shifts of 8 bytes are actually swaps. Convert accordingly.
7684 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
7685 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7686 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
7687 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
7691 if (Subtarget.hasQPX()) {
7692 if (VT.getVectorNumElements() != 4)
7695 if (V2.isUndef()) V2 = V1;
7697 int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7698 if (AlignIdx != -1) {
7699 return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7700 DAG.getConstant(AlignIdx, dl, MVT::i32));
7701 } else if (SVOp->isSplat()) {
7702 int SplatIdx = SVOp->getSplatIndex();
7703 if (SplatIdx >= 4) {
7708 return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7709 DAG.getConstant(SplatIdx, dl, MVT::i32));
7712 // Lower this into a qvgpci/qvfperm pair.
7714 // Compute the qvgpci literal
7716 for (unsigned i = 0; i < 4; ++i) {
7717 int m = SVOp->getMaskElt(i);
7718 unsigned mm = m >= 0 ? (unsigned) m : i;
7719 idx |= mm << (3-i)*3;
7722 SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7723 DAG.getConstant(idx, dl, MVT::i32));
7724 return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7727 // Cases that are handled by instructions that take permute immediates
7728 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7729 // selected by the instruction selector.
7731 if (PPC::isSplatShuffleMask(SVOp, 1) ||
7732 PPC::isSplatShuffleMask(SVOp, 2) ||
7733 PPC::isSplatShuffleMask(SVOp, 4) ||
7734 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7735 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7736 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7737 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7738 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7739 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7740 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7741 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7742 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7743 (Subtarget.hasP8Altivec() && (
7744 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7745 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
7746 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
7751 // Altivec has a variety of "shuffle immediates" that take two vector inputs
7752 // and produce a fixed permutation. If any of these match, do not lower to
7754 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7755 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7756 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7757 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7758 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7759 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7760 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7761 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7762 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7763 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7764 (Subtarget.hasP8Altivec() && (
7765 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7766 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
7767 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
7770 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
7771 // perfect shuffle table to emit an optimal matching sequence.
7772 ArrayRef<int> PermMask = SVOp->getMask();
7774 unsigned PFIndexes[4];
7775 bool isFourElementShuffle = true;
7776 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7777 unsigned EltNo = 8; // Start out undef.
7778 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
7779 if (PermMask[i*4+j] < 0)
7780 continue; // Undef, ignore it.
7782 unsigned ByteSource = PermMask[i*4+j];
7783 if ((ByteSource & 3) != j) {
7784 isFourElementShuffle = false;
7789 EltNo = ByteSource/4;
7790 } else if (EltNo != ByteSource/4) {
7791 isFourElementShuffle = false;
7795 PFIndexes[i] = EltNo;
7798 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7799 // perfect shuffle vector to determine if it is cost effective to do this as
7800 // discrete instructions, or whether we should use a vperm.
7801 // For now, we skip this for little endian until such time as we have a
7802 // little-endian perfect shuffle table.
7803 if (isFourElementShuffle && !isLittleEndian) {
7804 // Compute the index in the perfect shuffle table.
7805 unsigned PFTableIndex =
7806 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7808 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7809 unsigned Cost = (PFEntry >> 30);
7811 // Determining when to avoid vperm is tricky. Many things affect the cost
7812 // of vperm, particularly how many times the perm mask needs to be computed.
7813 // For example, if the perm mask can be hoisted out of a loop or is already
7814 // used (perhaps because there are multiple permutes with the same shuffle
7815 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
7816 // the loop requires an extra register.
7818 // As a compromise, we only emit discrete instructions if the shuffle can be
7819 // generated in 3 or fewer operations. When we have loop information
7820 // available, if this block is within a loop, we should avoid using vperm
7821 // for 3-operation perms and use a constant pool load instead.
7823 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7826 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7827 // vector that will get spilled to the constant pool.
7828 if (V2.isUndef()) V2 = V1;
7830 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7831 // that it is in input element units, not in bytes. Convert now.
7833 // For little endian, the order of the input vectors is reversed, and
7834 // the permutation mask is complemented with respect to 31. This is
7835 // necessary to produce proper semantics with the big-endian-biased vperm
7837 EVT EltVT = V1.getValueType().getVectorElementType();
7838 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7840 SmallVector<SDValue, 16> ResultMask;
7841 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7842 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7844 for (unsigned j = 0; j != BytesPerElement; ++j)
7846 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7849 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7853 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
7855 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7858 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7862 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
7863 /// vector comparison. If it is, return true and fill in Opc/isDot with
7864 /// information about the intrinsic.
7865 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
7866 bool &isDot, const PPCSubtarget &Subtarget) {
7867 unsigned IntrinsicID =
7868 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7871 switch (IntrinsicID) {
7874 // Comparison predicates.
7875 case Intrinsic::ppc_altivec_vcmpbfp_p:
7879 case Intrinsic::ppc_altivec_vcmpeqfp_p:
7883 case Intrinsic::ppc_altivec_vcmpequb_p:
7887 case Intrinsic::ppc_altivec_vcmpequh_p:
7891 case Intrinsic::ppc_altivec_vcmpequw_p:
7895 case Intrinsic::ppc_altivec_vcmpequd_p:
7896 if (Subtarget.hasP8Altivec()) {
7902 case Intrinsic::ppc_altivec_vcmpneb_p:
7903 case Intrinsic::ppc_altivec_vcmpneh_p:
7904 case Intrinsic::ppc_altivec_vcmpnew_p:
7905 case Intrinsic::ppc_altivec_vcmpnezb_p:
7906 case Intrinsic::ppc_altivec_vcmpnezh_p:
7907 case Intrinsic::ppc_altivec_vcmpnezw_p:
7908 if (Subtarget.hasP9Altivec()) {
7909 switch (IntrinsicID) {
7911 llvm_unreachable("Unknown comparison intrinsic.");
7912 case Intrinsic::ppc_altivec_vcmpneb_p:
7915 case Intrinsic::ppc_altivec_vcmpneh_p:
7918 case Intrinsic::ppc_altivec_vcmpnew_p:
7921 case Intrinsic::ppc_altivec_vcmpnezb_p:
7924 case Intrinsic::ppc_altivec_vcmpnezh_p:
7927 case Intrinsic::ppc_altivec_vcmpnezw_p:
7935 case Intrinsic::ppc_altivec_vcmpgefp_p:
7939 case Intrinsic::ppc_altivec_vcmpgtfp_p:
7943 case Intrinsic::ppc_altivec_vcmpgtsb_p:
7947 case Intrinsic::ppc_altivec_vcmpgtsh_p:
7951 case Intrinsic::ppc_altivec_vcmpgtsw_p:
7955 case Intrinsic::ppc_altivec_vcmpgtsd_p:
7956 if (Subtarget.hasP8Altivec()) {
7962 case Intrinsic::ppc_altivec_vcmpgtub_p:
7966 case Intrinsic::ppc_altivec_vcmpgtuh_p:
7970 case Intrinsic::ppc_altivec_vcmpgtuw_p:
7974 case Intrinsic::ppc_altivec_vcmpgtud_p:
7975 if (Subtarget.hasP8Altivec()) {
7982 // VSX predicate comparisons use the same infrastructure
7983 case Intrinsic::ppc_vsx_xvcmpeqdp_p:
7984 case Intrinsic::ppc_vsx_xvcmpgedp_p:
7985 case Intrinsic::ppc_vsx_xvcmpgtdp_p:
7986 case Intrinsic::ppc_vsx_xvcmpeqsp_p:
7987 case Intrinsic::ppc_vsx_xvcmpgesp_p:
7988 case Intrinsic::ppc_vsx_xvcmpgtsp_p:
7989 if (Subtarget.hasVSX()) {
7990 switch (IntrinsicID) {
7991 case Intrinsic::ppc_vsx_xvcmpeqdp_p:
7994 case Intrinsic::ppc_vsx_xvcmpgedp_p:
7997 case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8000 case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8003 case Intrinsic::ppc_vsx_xvcmpgesp_p:
8006 case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8015 // Normal Comparisons.
8016 case Intrinsic::ppc_altivec_vcmpbfp:
8019 case Intrinsic::ppc_altivec_vcmpeqfp:
8022 case Intrinsic::ppc_altivec_vcmpequb:
8025 case Intrinsic::ppc_altivec_vcmpequh:
8028 case Intrinsic::ppc_altivec_vcmpequw:
8031 case Intrinsic::ppc_altivec_vcmpequd:
8032 if (Subtarget.hasP8Altivec())
8037 case Intrinsic::ppc_altivec_vcmpneb:
8038 case Intrinsic::ppc_altivec_vcmpneh:
8039 case Intrinsic::ppc_altivec_vcmpnew:
8040 case Intrinsic::ppc_altivec_vcmpnezb:
8041 case Intrinsic::ppc_altivec_vcmpnezh:
8042 case Intrinsic::ppc_altivec_vcmpnezw:
8043 if (Subtarget.hasP9Altivec())
8044 switch (IntrinsicID) {
8046 llvm_unreachable("Unknown comparison intrinsic.");
8047 case Intrinsic::ppc_altivec_vcmpneb:
8050 case Intrinsic::ppc_altivec_vcmpneh:
8053 case Intrinsic::ppc_altivec_vcmpnew:
8056 case Intrinsic::ppc_altivec_vcmpnezb:
8059 case Intrinsic::ppc_altivec_vcmpnezh:
8062 case Intrinsic::ppc_altivec_vcmpnezw:
8069 case Intrinsic::ppc_altivec_vcmpgefp:
8072 case Intrinsic::ppc_altivec_vcmpgtfp:
8075 case Intrinsic::ppc_altivec_vcmpgtsb:
8078 case Intrinsic::ppc_altivec_vcmpgtsh:
8081 case Intrinsic::ppc_altivec_vcmpgtsw:
8084 case Intrinsic::ppc_altivec_vcmpgtsd:
8085 if (Subtarget.hasP8Altivec())
8090 case Intrinsic::ppc_altivec_vcmpgtub:
8093 case Intrinsic::ppc_altivec_vcmpgtuh:
8096 case Intrinsic::ppc_altivec_vcmpgtuw:
8099 case Intrinsic::ppc_altivec_vcmpgtud:
8100 if (Subtarget.hasP8Altivec())
8109 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
8110 /// lower, do it, otherwise return null.
8111 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
8112 SelectionDAG &DAG) const {
8113 unsigned IntrinsicID =
8114 cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8116 if (IntrinsicID == Intrinsic::thread_pointer) {
8117 // Reads the thread pointer register, used for __builtin_thread_pointer.
8118 bool is64bit = Subtarget.isPPC64();
8119 return DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
8120 is64bit ? MVT::i64 : MVT::i32);
8123 // If this is a lowered altivec predicate compare, CompareOpc is set to the
8124 // opcode number of the comparison.
8128 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
8129 return SDValue(); // Don't custom lower most intrinsics.
8131 // If this is a non-dot comparison, make the VCMP node and we are done.
8133 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
8134 Op.getOperand(1), Op.getOperand(2),
8135 DAG.getConstant(CompareOpc, dl, MVT::i32));
8136 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
8139 // Create the PPCISD altivec 'dot' comparison node.
8141 Op.getOperand(2), // LHS
8142 Op.getOperand(3), // RHS
8143 DAG.getConstant(CompareOpc, dl, MVT::i32)
8145 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
8146 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8148 // Now that we have the comparison, emit a copy from the CR to a GPR.
8149 // This is flagged to the above dot comparison.
8150 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
8151 DAG.getRegister(PPC::CR6, MVT::i32),
8152 CompNode.getValue(1));
8154 // Unpack the result based on how the target uses it.
8155 unsigned BitNo; // Bit # of CR6.
8156 bool InvertBit; // Invert result?
8157 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
8158 default: // Can't happen, don't crash on invalid number though.
8159 case 0: // Return the value of the EQ bit of CR6.
8160 BitNo = 0; InvertBit = false;
8162 case 1: // Return the inverted value of the EQ bit of CR6.
8163 BitNo = 0; InvertBit = true;
8165 case 2: // Return the value of the LT bit of CR6.
8166 BitNo = 2; InvertBit = false;
8168 case 3: // Return the inverted value of the LT bit of CR6.
8169 BitNo = 2; InvertBit = true;
8173 // Shift the bit into the low position.
8174 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
8175 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
8177 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
8178 DAG.getConstant(1, dl, MVT::i32));
8180 // If we are supposed to, toggle the bit.
8182 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
8183 DAG.getConstant(1, dl, MVT::i32));
8187 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
8188 SelectionDAG &DAG) const {
8190 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
8191 // instructions), but for smaller types, we need to first extend up to v2i32
8192 // before doing going farther.
8193 if (Op.getValueType() == MVT::v2i64) {
8194 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
8195 if (ExtVT != MVT::v2i32) {
8196 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
8197 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
8198 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
8199 ExtVT.getVectorElementType(), 4)));
8200 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
8201 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
8202 DAG.getValueType(MVT::v2i32));
8211 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
8212 SelectionDAG &DAG) const {
8214 // Create a stack slot that is 16-byte aligned.
8215 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8216 int FrameIdx = MFI.CreateStackObject(16, 16, false);
8217 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8218 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8220 // Store the input value into Value#0 of the stack slot.
8221 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8222 MachinePointerInfo());
8224 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
8227 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8228 SelectionDAG &DAG) const {
8229 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
8230 "Should only be called for ISD::INSERT_VECTOR_ELT");
8231 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8232 // We have legal lowering for constant indices but not for variable ones.
8238 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8239 SelectionDAG &DAG) const {
8241 SDNode *N = Op.getNode();
8243 assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
8244 "Unknown extract_vector_elt type");
8246 SDValue Value = N->getOperand(0);
8248 // The first part of this is like the store lowering except that we don't
8249 // need to track the chain.
8251 // The values are now known to be -1 (false) or 1 (true). To convert this
8252 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8253 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8254 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8256 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8257 // understand how to form the extending load.
8258 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8260 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8262 // Now convert to an integer and store.
8263 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8264 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8267 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8268 int FrameIdx = MFI.CreateStackObject(16, 16, false);
8269 MachinePointerInfo PtrInfo =
8270 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8271 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8272 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8274 SDValue StoreChain = DAG.getEntryNode();
8275 SDValue Ops[] = {StoreChain,
8276 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8278 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8280 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8281 dl, VTs, Ops, MVT::v4i32, PtrInfo);
8283 // Extract the value requested.
8284 unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8285 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8286 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8289 DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
8291 if (!Subtarget.useCRBits())
8294 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
8297 /// Lowering for QPX v4i1 loads
8298 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
8299 SelectionDAG &DAG) const {
8301 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
8302 SDValue LoadChain = LN->getChain();
8303 SDValue BasePtr = LN->getBasePtr();
8305 if (Op.getValueType() == MVT::v4f64 ||
8306 Op.getValueType() == MVT::v4f32) {
8307 EVT MemVT = LN->getMemoryVT();
8308 unsigned Alignment = LN->getAlignment();
8310 // If this load is properly aligned, then it is legal.
8311 if (Alignment >= MemVT.getStoreSize())
8314 EVT ScalarVT = Op.getValueType().getScalarType(),
8315 ScalarMemVT = MemVT.getScalarType();
8316 unsigned Stride = ScalarMemVT.getStoreSize();
8318 SDValue Vals[4], LoadChains[4];
8319 for (unsigned Idx = 0; Idx < 4; ++Idx) {
8321 if (ScalarVT != ScalarMemVT)
8322 Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
8324 LN->getPointerInfo().getWithOffset(Idx * Stride),
8325 ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8326 LN->getMemOperand()->getFlags(), LN->getAAInfo());
8328 Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
8329 LN->getPointerInfo().getWithOffset(Idx * Stride),
8330 MinAlign(Alignment, Idx * Stride),
8331 LN->getMemOperand()->getFlags(), LN->getAAInfo());
8333 if (Idx == 0 && LN->isIndexed()) {
8334 assert(LN->getAddressingMode() == ISD::PRE_INC &&
8335 "Unknown addressing mode on vector load");
8336 Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
8337 LN->getAddressingMode());
8341 LoadChains[Idx] = Load.getValue(1);
8343 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8344 DAG.getConstant(Stride, dl,
8345 BasePtr.getValueType()));
8348 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8349 SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
8351 if (LN->isIndexed()) {
8352 SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
8353 return DAG.getMergeValues(RetOps, dl);
8356 SDValue RetOps[] = { Value, TF };
8357 return DAG.getMergeValues(RetOps, dl);
8360 assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
8361 assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
8363 // To lower v4i1 from a byte array, we load the byte elements of the
8364 // vector and then reuse the BUILD_VECTOR logic.
8366 SDValue VectElmts[4], VectElmtChains[4];
8367 for (unsigned i = 0; i < 4; ++i) {
8368 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8369 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8371 VectElmts[i] = DAG.getExtLoad(
8372 ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
8373 LN->getPointerInfo().getWithOffset(i), MVT::i8,
8374 /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
8375 VectElmtChains[i] = VectElmts[i].getValue(1);
8378 LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
8379 SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
8381 SDValue RVals[] = { Value, LoadChain };
8382 return DAG.getMergeValues(RVals, dl);
8385 /// Lowering for QPX v4i1 stores
8386 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
8387 SelectionDAG &DAG) const {
8389 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
8390 SDValue StoreChain = SN->getChain();
8391 SDValue BasePtr = SN->getBasePtr();
8392 SDValue Value = SN->getValue();
8394 if (Value.getValueType() == MVT::v4f64 ||
8395 Value.getValueType() == MVT::v4f32) {
8396 EVT MemVT = SN->getMemoryVT();
8397 unsigned Alignment = SN->getAlignment();
8399 // If this store is properly aligned, then it is legal.
8400 if (Alignment >= MemVT.getStoreSize())
8403 EVT ScalarVT = Value.getValueType().getScalarType(),
8404 ScalarMemVT = MemVT.getScalarType();
8405 unsigned Stride = ScalarMemVT.getStoreSize();
8408 for (unsigned Idx = 0; Idx < 4; ++Idx) {
8409 SDValue Ex = DAG.getNode(
8410 ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
8411 DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
8413 if (ScalarVT != ScalarMemVT)
8415 DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
8416 SN->getPointerInfo().getWithOffset(Idx * Stride),
8417 ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8418 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8420 Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
8421 SN->getPointerInfo().getWithOffset(Idx * Stride),
8422 MinAlign(Alignment, Idx * Stride),
8423 SN->getMemOperand()->getFlags(), SN->getAAInfo());
8425 if (Idx == 0 && SN->isIndexed()) {
8426 assert(SN->getAddressingMode() == ISD::PRE_INC &&
8427 "Unknown addressing mode on vector store");
8428 Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
8429 SN->getAddressingMode());
8432 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8433 DAG.getConstant(Stride, dl,
8434 BasePtr.getValueType()));
8435 Stores[Idx] = Store;
8438 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8440 if (SN->isIndexed()) {
8441 SDValue RetOps[] = { TF, Stores[0].getValue(1) };
8442 return DAG.getMergeValues(RetOps, dl);
8448 assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
8449 assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
8451 // The values are now known to be -1 (false) or 1 (true). To convert this
8452 // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8453 // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8454 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8456 // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8457 // understand how to form the extending load.
8458 SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8460 Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8462 // Now convert to an integer and store.
8463 Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8464 DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8467 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8468 int FrameIdx = MFI.CreateStackObject(16, 16, false);
8469 MachinePointerInfo PtrInfo =
8470 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8471 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8472 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8474 SDValue Ops[] = {StoreChain,
8475 DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8477 SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8479 StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8480 dl, VTs, Ops, MVT::v4i32, PtrInfo);
8482 // Move data into the byte array.
8483 SDValue Loads[4], LoadChains[4];
8484 for (unsigned i = 0; i < 4; ++i) {
8485 unsigned Offset = 4*i;
8486 SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8487 Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8489 Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
8490 PtrInfo.getWithOffset(Offset));
8491 LoadChains[i] = Loads[i].getValue(1);
8494 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8497 for (unsigned i = 0; i < 4; ++i) {
8498 SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8499 Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8501 Stores[i] = DAG.getTruncStore(
8502 StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
8503 MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
8507 StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8512 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
8514 if (Op.getValueType() == MVT::v4i32) {
8515 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8517 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
8518 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
8520 SDValue RHSSwap = // = vrlw RHS, 16
8521 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
8523 // Shrinkify inputs to v8i16.
8524 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
8525 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
8526 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
8528 // Low parts multiplied together, generating 32-bit results (we ignore the
8530 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
8531 LHS, RHS, DAG, dl, MVT::v4i32);
8533 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
8534 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
8535 // Shift the high parts up 16 bits.
8536 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
8538 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
8539 } else if (Op.getValueType() == MVT::v8i16) {
8540 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8542 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
8544 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
8545 LHS, RHS, Zero, DAG, dl);
8546 } else if (Op.getValueType() == MVT::v16i8) {
8547 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8548 bool isLittleEndian = Subtarget.isLittleEndian();
8550 // Multiply the even 8-bit parts, producing 16-bit sums.
8551 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
8552 LHS, RHS, DAG, dl, MVT::v8i16);
8553 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
8555 // Multiply the odd 8-bit parts, producing 16-bit sums.
8556 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
8557 LHS, RHS, DAG, dl, MVT::v8i16);
8558 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
8560 // Merge the results together. Because vmuleub and vmuloub are
8561 // instructions with a big-endian bias, we must reverse the
8562 // element numbering and reverse the meaning of "odd" and "even"
8563 // when generating little endian code.
8565 for (unsigned i = 0; i != 8; ++i) {
8566 if (isLittleEndian) {
8568 Ops[i*2+1] = 2*i+16;
8571 Ops[i*2+1] = 2*i+1+16;
8575 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
8577 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
8579 llvm_unreachable("Unknown mul to lower!");
8583 /// LowerOperation - Provide custom lowering hooks for some operations.
8585 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8586 switch (Op.getOpcode()) {
8587 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
8588 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8589 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8590 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8591 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8592 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
8593 case ISD::SETCC: return LowerSETCC(Op, DAG);
8594 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
8595 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
8597 return LowerVASTART(Op, DAG);
8600 return LowerVAARG(Op, DAG);
8603 return LowerVACOPY(Op, DAG);
8605 case ISD::STACKRESTORE:
8606 return LowerSTACKRESTORE(Op, DAG);
8608 case ISD::DYNAMIC_STACKALLOC:
8609 return LowerDYNAMIC_STACKALLOC(Op, DAG);
8611 case ISD::GET_DYNAMIC_AREA_OFFSET:
8612 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
8614 case ISD::EH_DWARF_CFA:
8615 return LowerEH_DWARF_CFA(Op, DAG);
8617 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
8618 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
8620 case ISD::LOAD: return LowerLOAD(Op, DAG);
8621 case ISD::STORE: return LowerSTORE(Op, DAG);
8622 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
8623 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
8624 case ISD::FP_TO_UINT:
8625 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
8627 case ISD::UINT_TO_FP:
8628 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
8629 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8631 // Lower 64-bit shifts.
8632 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
8633 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
8634 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
8636 // Vector-related lowering.
8637 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
8638 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8639 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8640 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
8641 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
8642 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8643 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8644 case ISD::MUL: return LowerMUL(Op, DAG);
8646 // For counter-based loop handling.
8647 case ISD::INTRINSIC_W_CHAIN: return SDValue();
8649 // Frame & Return address.
8650 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8651 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8655 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
8656 SmallVectorImpl<SDValue>&Results,
8657 SelectionDAG &DAG) const {
8659 switch (N->getOpcode()) {
8661 llvm_unreachable("Do not know how to custom type legalize this operation!");
8662 case ISD::READCYCLECOUNTER: {
8663 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8664 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
8666 Results.push_back(RTB);
8667 Results.push_back(RTB.getValue(1));
8668 Results.push_back(RTB.getValue(2));
8671 case ISD::INTRINSIC_W_CHAIN: {
8672 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
8673 Intrinsic::ppc_is_decremented_ctr_nonzero)
8676 assert(N->getValueType(0) == MVT::i1 &&
8677 "Unexpected result type for CTR decrement intrinsic");
8678 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
8679 N->getValueType(0));
8680 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
8681 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
8684 Results.push_back(NewInt);
8685 Results.push_back(NewInt.getValue(1));
8689 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
8692 EVT VT = N->getValueType(0);
8694 if (VT == MVT::i64) {
8695 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
8697 Results.push_back(NewNode);
8698 Results.push_back(NewNode.getValue(1));
8702 case ISD::FP_ROUND_INREG: {
8703 assert(N->getValueType(0) == MVT::ppcf128);
8704 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
8705 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8706 MVT::f64, N->getOperand(0),
8707 DAG.getIntPtrConstant(0, dl));
8708 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8709 MVT::f64, N->getOperand(0),
8710 DAG.getIntPtrConstant(1, dl));
8712 // Add the two halves of the long double in round-to-zero mode.
8713 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8715 // We know the low half is about to be thrown away, so just use something
8717 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8721 case ISD::FP_TO_SINT:
8722 case ISD::FP_TO_UINT:
8723 // LowerFP_TO_INT() can only handle f32 and f64.
8724 if (N->getOperand(0).getValueType() == MVT::ppcf128)
8726 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8731 //===----------------------------------------------------------------------===//
8732 // Other Lowering Code
8733 //===----------------------------------------------------------------------===//
8735 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8736 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8737 Function *Func = Intrinsic::getDeclaration(M, Id);
8738 return Builder.CreateCall(Func, {});
8741 // The mappings for emitLeading/TrailingFence is taken from
8742 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8743 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8745 AtomicOrdering Ord) const {
8746 if (Ord == AtomicOrdering::SequentiallyConsistent)
8747 return callIntrinsic(Builder, Intrinsic::ppc_sync);
8748 if (isReleaseOrStronger(Ord))
8749 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8753 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8755 AtomicOrdering Ord) const {
8756 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord))
8757 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8758 // FIXME: this is too conservative, a dependent branch + isync is enough.
8759 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8760 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8761 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8766 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
8767 unsigned AtomicSize,
8770 unsigned CmpPred) const {
8771 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8772 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8774 auto LoadMnemonic = PPC::LDARX;
8775 auto StoreMnemonic = PPC::STDCX;
8776 switch (AtomicSize) {
8778 llvm_unreachable("Unexpected size of atomic entity");
8780 LoadMnemonic = PPC::LBARX;
8781 StoreMnemonic = PPC::STBCX;
8782 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8785 LoadMnemonic = PPC::LHARX;
8786 StoreMnemonic = PPC::STHCX;
8787 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8790 LoadMnemonic = PPC::LWARX;
8791 StoreMnemonic = PPC::STWCX;
8794 LoadMnemonic = PPC::LDARX;
8795 StoreMnemonic = PPC::STDCX;
8799 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8800 MachineFunction *F = BB->getParent();
8801 MachineFunction::iterator It = ++BB->getIterator();
8803 unsigned dest = MI.getOperand(0).getReg();
8804 unsigned ptrA = MI.getOperand(1).getReg();
8805 unsigned ptrB = MI.getOperand(2).getReg();
8806 unsigned incr = MI.getOperand(3).getReg();
8807 DebugLoc dl = MI.getDebugLoc();
8809 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8810 MachineBasicBlock *loop2MBB =
8811 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8812 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8813 F->insert(It, loopMBB);
8815 F->insert(It, loop2MBB);
8816 F->insert(It, exitMBB);
8817 exitMBB->splice(exitMBB->begin(), BB,
8818 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8819 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8821 MachineRegisterInfo &RegInfo = F->getRegInfo();
8822 unsigned TmpReg = (!BinOpcode) ? incr :
8823 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8824 : &PPC::GPRCRegClass);
8828 // fallthrough --> loopMBB
8829 BB->addSuccessor(loopMBB);
8832 // l[wd]arx dest, ptr
8833 // add r0, dest, incr
8834 // st[wd]cx. r0, ptr
8836 // fallthrough --> exitMBB
8840 // l[wd]arx dest, ptr
8841 // cmpl?[wd] incr, dest
8844 // st[wd]cx. dest, ptr
8846 // fallthrough --> exitMBB
8849 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8850 .addReg(ptrA).addReg(ptrB);
8852 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8854 // Signed comparisons of byte or halfword values must be sign-extended.
8855 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
8856 unsigned ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8857 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
8858 ExtReg).addReg(dest);
8859 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8860 .addReg(incr).addReg(ExtReg);
8862 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8863 .addReg(incr).addReg(dest);
8865 BuildMI(BB, dl, TII->get(PPC::BCC))
8866 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
8867 BB->addSuccessor(loop2MBB);
8868 BB->addSuccessor(exitMBB);
8871 BuildMI(BB, dl, TII->get(StoreMnemonic))
8872 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
8873 BuildMI(BB, dl, TII->get(PPC::BCC))
8874 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8875 BB->addSuccessor(loopMBB);
8876 BB->addSuccessor(exitMBB);
8885 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
8886 MachineBasicBlock *BB,
8887 bool is8bit, // operation
8890 unsigned CmpPred) const {
8891 // If we support part-word atomic mnemonics, just use them
8892 if (Subtarget.hasPartwordAtomics())
8893 return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode,
8894 CmpOpcode, CmpPred);
8896 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8897 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8898 // In 64 bit mode we have to use 64 bits for addresses, even though the
8899 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
8900 // registers without caring whether they're 32 or 64, but here we're
8901 // doing actual arithmetic on the addresses.
8902 bool is64bit = Subtarget.isPPC64();
8903 bool isLittleEndian = Subtarget.isLittleEndian();
8904 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8906 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8907 MachineFunction *F = BB->getParent();
8908 MachineFunction::iterator It = ++BB->getIterator();
8910 unsigned dest = MI.getOperand(0).getReg();
8911 unsigned ptrA = MI.getOperand(1).getReg();
8912 unsigned ptrB = MI.getOperand(2).getReg();
8913 unsigned incr = MI.getOperand(3).getReg();
8914 DebugLoc dl = MI.getDebugLoc();
8916 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8917 MachineBasicBlock *loop2MBB =
8918 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8919 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8920 F->insert(It, loopMBB);
8922 F->insert(It, loop2MBB);
8923 F->insert(It, exitMBB);
8924 exitMBB->splice(exitMBB->begin(), BB,
8925 std::next(MachineBasicBlock::iterator(MI)), BB->end());
8926 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8928 MachineRegisterInfo &RegInfo = F->getRegInfo();
8929 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8930 : &PPC::GPRCRegClass;
8931 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8932 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8934 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
8935 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8936 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8937 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8938 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8939 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8940 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8941 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8942 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8944 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8948 // fallthrough --> loopMBB
8949 BB->addSuccessor(loopMBB);
8951 // The 4-byte load must be aligned, while a char or short may be
8952 // anywhere in the word. Hence all this nasty bookkeeping code.
8953 // add ptr1, ptrA, ptrB [copy if ptrA==0]
8954 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
8955 // xori shift, shift1, 24 [16]
8956 // rlwinm ptr, ptr1, 0, 0, 29
8957 // slw incr2, incr, shift
8958 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
8959 // slw mask, mask2, shift
8961 // lwarx tmpDest, ptr
8962 // add tmp, tmpDest, incr2
8963 // andc tmp2, tmpDest, mask
8964 // and tmp3, tmp, mask
8965 // or tmp4, tmp3, tmp2
8968 // fallthrough --> exitMBB
8969 // srw dest, tmpDest, shift
8970 if (ptrA != ZeroReg) {
8971 Ptr1Reg = RegInfo.createVirtualRegister(RC);
8972 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
8973 .addReg(ptrA).addReg(ptrB);
8977 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
8978 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
8979 if (!isLittleEndian)
8980 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
8981 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
8983 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
8984 .addReg(Ptr1Reg).addImm(0).addImm(61);
8986 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
8987 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
8988 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
8989 .addReg(incr).addReg(ShiftReg);
8991 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
8993 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
8994 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
8996 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
8997 .addReg(Mask2Reg).addReg(ShiftReg);
9000 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9001 .addReg(ZeroReg).addReg(PtrReg);
9003 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
9004 .addReg(Incr2Reg).addReg(TmpDestReg);
9005 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
9006 .addReg(TmpDestReg).addReg(MaskReg);
9007 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
9008 .addReg(TmpReg).addReg(MaskReg);
9010 // For unsigned comparisons, we can directly compare the shifted values.
9011 // For signed comparisons we shift and sign extend.
9012 unsigned SReg = RegInfo.createVirtualRegister(RC);
9013 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg)
9014 .addReg(TmpDestReg).addReg(MaskReg);
9015 unsigned ValueReg = SReg;
9016 unsigned CmpReg = Incr2Reg;
9017 if (CmpOpcode == PPC::CMPW) {
9018 ValueReg = RegInfo.createVirtualRegister(RC);
9019 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
9020 .addReg(SReg).addReg(ShiftReg);
9021 unsigned ValueSReg = RegInfo.createVirtualRegister(RC);
9022 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
9024 ValueReg = ValueSReg;
9027 BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9028 .addReg(CmpReg).addReg(ValueReg);
9029 BuildMI(BB, dl, TII->get(PPC::BCC))
9030 .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9031 BB->addSuccessor(loop2MBB);
9032 BB->addSuccessor(exitMBB);
9035 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
9036 .addReg(Tmp3Reg).addReg(Tmp2Reg);
9037 BuildMI(BB, dl, TII->get(PPC::STWCX))
9038 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
9039 BuildMI(BB, dl, TII->get(PPC::BCC))
9040 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9041 BB->addSuccessor(loopMBB);
9042 BB->addSuccessor(exitMBB);
9047 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
9052 llvm::MachineBasicBlock *
9053 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
9054 MachineBasicBlock *MBB) const {
9055 DebugLoc DL = MI.getDebugLoc();
9056 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9057 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
9059 MachineFunction *MF = MBB->getParent();
9060 MachineRegisterInfo &MRI = MF->getRegInfo();
9062 const BasicBlock *BB = MBB->getBasicBlock();
9063 MachineFunction::iterator I = ++MBB->getIterator();
9066 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9067 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9069 unsigned DstReg = MI.getOperand(0).getReg();
9070 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
9071 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
9072 unsigned mainDstReg = MRI.createVirtualRegister(RC);
9073 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
9075 MVT PVT = getPointerTy(MF->getDataLayout());
9076 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9077 "Invalid Pointer Size!");
9078 // For v = setjmp(buf), we generate
9081 // SjLjSetup mainMBB
9087 // buf[LabelOffset] = LR
9091 // v = phi(main, restore)
9094 MachineBasicBlock *thisMBB = MBB;
9095 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
9096 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
9097 MF->insert(I, mainMBB);
9098 MF->insert(I, sinkMBB);
9100 MachineInstrBuilder MIB;
9102 // Transfer the remainder of BB and its successor edges to sinkMBB.
9103 sinkMBB->splice(sinkMBB->begin(), MBB,
9104 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9105 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
9107 // Note that the structure of the jmp_buf used here is not compatible
9108 // with that used by libc, and is not designed to be. Specifically, it
9109 // stores only those 'reserved' registers that LLVM does not otherwise
9110 // understand how to spill. Also, by convention, by the time this
9111 // intrinsic is called, Clang has already stored the frame address in the
9112 // first slot of the buffer and stack address in the third. Following the
9113 // X86 target code, we'll store the jump address in the second slot. We also
9114 // need to save the TOC pointer (R2) to handle jumps between shared
9115 // libraries, and that will be stored in the fourth slot. The thread
9116 // identifier (R13) is not affected.
9119 const int64_t LabelOffset = 1 * PVT.getStoreSize();
9120 const int64_t TOCOffset = 3 * PVT.getStoreSize();
9121 const int64_t BPOffset = 4 * PVT.getStoreSize();
9123 // Prepare IP either in reg.
9124 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
9125 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
9126 unsigned BufReg = MI.getOperand(1).getReg();
9128 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
9129 setUsesTOCBasePtr(*MBB->getParent());
9130 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
9134 MIB.setMemRefs(MMOBegin, MMOEnd);
9137 // Naked functions never have a base pointer, and so we use r1. For all
9138 // other functions, this decision must be delayed until during PEI.
9140 if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
9141 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
9143 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
9145 MIB = BuildMI(*thisMBB, MI, DL,
9146 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
9150 MIB.setMemRefs(MMOBegin, MMOEnd);
9153 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
9154 MIB.addRegMask(TRI->getNoPreservedMask());
9156 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
9158 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
9160 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
9162 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
9163 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
9168 BuildMI(mainMBB, DL,
9169 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
9172 if (Subtarget.isPPC64()) {
9173 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
9175 .addImm(LabelOffset)
9178 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
9180 .addImm(LabelOffset)
9184 MIB.setMemRefs(MMOBegin, MMOEnd);
9186 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
9187 mainMBB->addSuccessor(sinkMBB);
9190 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9191 TII->get(PPC::PHI), DstReg)
9192 .addReg(mainDstReg).addMBB(mainMBB)
9193 .addReg(restoreDstReg).addMBB(thisMBB);
9195 MI.eraseFromParent();
9200 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
9201 MachineBasicBlock *MBB) const {
9202 DebugLoc DL = MI.getDebugLoc();
9203 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9205 MachineFunction *MF = MBB->getParent();
9206 MachineRegisterInfo &MRI = MF->getRegInfo();
9209 MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9210 MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9212 MVT PVT = getPointerTy(MF->getDataLayout());
9213 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9214 "Invalid Pointer Size!");
9216 const TargetRegisterClass *RC =
9217 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
9218 unsigned Tmp = MRI.createVirtualRegister(RC);
9219 // Since FP is only updated here but NOT referenced, it's treated as GPR.
9220 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
9221 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
9225 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
9228 MachineInstrBuilder MIB;
9230 const int64_t LabelOffset = 1 * PVT.getStoreSize();
9231 const int64_t SPOffset = 2 * PVT.getStoreSize();
9232 const int64_t TOCOffset = 3 * PVT.getStoreSize();
9233 const int64_t BPOffset = 4 * PVT.getStoreSize();
9235 unsigned BufReg = MI.getOperand(0).getReg();
9237 // Reload FP (the jumped-to function may not have had a
9238 // frame pointer, and if so, then its r31 will be restored
9240 if (PVT == MVT::i64) {
9241 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
9245 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
9249 MIB.setMemRefs(MMOBegin, MMOEnd);
9252 if (PVT == MVT::i64) {
9253 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
9254 .addImm(LabelOffset)
9257 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
9258 .addImm(LabelOffset)
9261 MIB.setMemRefs(MMOBegin, MMOEnd);
9264 if (PVT == MVT::i64) {
9265 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
9269 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
9273 MIB.setMemRefs(MMOBegin, MMOEnd);
9276 if (PVT == MVT::i64) {
9277 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
9281 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
9285 MIB.setMemRefs(MMOBegin, MMOEnd);
9288 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
9289 setUsesTOCBasePtr(*MBB->getParent());
9290 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
9294 MIB.setMemRefs(MMOBegin, MMOEnd);
9298 BuildMI(*MBB, MI, DL,
9299 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
9300 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
9302 MI.eraseFromParent();
9307 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9308 MachineBasicBlock *BB) const {
9309 if (MI.getOpcode() == TargetOpcode::STACKMAP ||
9310 MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9311 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
9312 MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9313 // Call lowering should have added an r2 operand to indicate a dependence
9314 // on the TOC base pointer value. It can't however, because there is no
9315 // way to mark the dependence as implicit there, and so the stackmap code
9316 // will confuse it with a regular operand. Instead, add the dependence
9318 setUsesTOCBasePtr(*BB->getParent());
9319 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
9322 return emitPatchPoint(MI, BB);
9325 if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
9326 MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
9327 return emitEHSjLjSetJmp(MI, BB);
9328 } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
9329 MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
9330 return emitEHSjLjLongJmp(MI, BB);
9333 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9335 // To "insert" these instructions we actually have to insert their
9336 // control-flow patterns.
9337 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9338 MachineFunction::iterator It = ++BB->getIterator();
9340 MachineFunction *F = BB->getParent();
9342 if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9343 MI.getOpcode() == PPC::SELECT_CC_I8 ||
9344 MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) {
9345 SmallVector<MachineOperand, 2> Cond;
9346 if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9347 MI.getOpcode() == PPC::SELECT_CC_I8)
9348 Cond.push_back(MI.getOperand(4));
9350 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
9351 Cond.push_back(MI.getOperand(1));
9353 DebugLoc dl = MI.getDebugLoc();
9354 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
9355 MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
9356 } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9357 MI.getOpcode() == PPC::SELECT_CC_I8 ||
9358 MI.getOpcode() == PPC::SELECT_CC_F4 ||
9359 MI.getOpcode() == PPC::SELECT_CC_F8 ||
9360 MI.getOpcode() == PPC::SELECT_CC_QFRC ||
9361 MI.getOpcode() == PPC::SELECT_CC_QSRC ||
9362 MI.getOpcode() == PPC::SELECT_CC_QBRC ||
9363 MI.getOpcode() == PPC::SELECT_CC_VRRC ||
9364 MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
9365 MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
9366 MI.getOpcode() == PPC::SELECT_CC_VSRC ||
9367 MI.getOpcode() == PPC::SELECT_I4 ||
9368 MI.getOpcode() == PPC::SELECT_I8 ||
9369 MI.getOpcode() == PPC::SELECT_F4 ||
9370 MI.getOpcode() == PPC::SELECT_F8 ||
9371 MI.getOpcode() == PPC::SELECT_QFRC ||
9372 MI.getOpcode() == PPC::SELECT_QSRC ||
9373 MI.getOpcode() == PPC::SELECT_QBRC ||
9374 MI.getOpcode() == PPC::SELECT_VRRC ||
9375 MI.getOpcode() == PPC::SELECT_VSFRC ||
9376 MI.getOpcode() == PPC::SELECT_VSSRC ||
9377 MI.getOpcode() == PPC::SELECT_VSRC) {
9378 // The incoming instruction knows the destination vreg to set, the
9379 // condition code register to branch on, the true/false values to
9380 // select between, and a branch opcode to use.
9385 // cmpTY ccX, r1, r2
9387 // fallthrough --> copy0MBB
9388 MachineBasicBlock *thisMBB = BB;
9389 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9390 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9391 DebugLoc dl = MI.getDebugLoc();
9392 F->insert(It, copy0MBB);
9393 F->insert(It, sinkMBB);
9395 // Transfer the remainder of BB and its successor edges to sinkMBB.
9396 sinkMBB->splice(sinkMBB->begin(), BB,
9397 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9398 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9400 // Next, add the true and fallthrough blocks as its successors.
9401 BB->addSuccessor(copy0MBB);
9402 BB->addSuccessor(sinkMBB);
9404 if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
9405 MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
9406 MI.getOpcode() == PPC::SELECT_QFRC ||
9407 MI.getOpcode() == PPC::SELECT_QSRC ||
9408 MI.getOpcode() == PPC::SELECT_QBRC ||
9409 MI.getOpcode() == PPC::SELECT_VRRC ||
9410 MI.getOpcode() == PPC::SELECT_VSFRC ||
9411 MI.getOpcode() == PPC::SELECT_VSSRC ||
9412 MI.getOpcode() == PPC::SELECT_VSRC) {
9413 BuildMI(BB, dl, TII->get(PPC::BC))
9414 .addReg(MI.getOperand(1).getReg())
9417 unsigned SelectPred = MI.getOperand(4).getImm();
9418 BuildMI(BB, dl, TII->get(PPC::BCC))
9420 .addReg(MI.getOperand(1).getReg())
9425 // %FalseValue = ...
9426 // # fallthrough to sinkMBB
9429 // Update machine-CFG edges
9430 BB->addSuccessor(sinkMBB);
9433 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9436 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
9437 .addReg(MI.getOperand(3).getReg())
9439 .addReg(MI.getOperand(2).getReg())
9441 } else if (MI.getOpcode() == PPC::ReadTB) {
9442 // To read the 64-bit time-base register on a 32-bit target, we read the
9443 // two halves. Should the counter have wrapped while it was being read, we
9444 // need to try again.
9447 // mfspr Rx,TBU # load from TBU
9448 // mfspr Ry,TB # load from TB
9449 // mfspr Rz,TBU # load from TBU
9450 // cmpw crX,Rx,Rz # check if 'old'='new'
9451 // bne readLoop # branch if they're not equal
9454 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
9455 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9456 DebugLoc dl = MI.getDebugLoc();
9457 F->insert(It, readMBB);
9458 F->insert(It, sinkMBB);
9460 // Transfer the remainder of BB and its successor edges to sinkMBB.
9461 sinkMBB->splice(sinkMBB->begin(), BB,
9462 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9463 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9465 BB->addSuccessor(readMBB);
9468 MachineRegisterInfo &RegInfo = F->getRegInfo();
9469 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9470 unsigned LoReg = MI.getOperand(0).getReg();
9471 unsigned HiReg = MI.getOperand(1).getReg();
9473 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
9474 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
9475 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
9477 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9479 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
9480 .addReg(HiReg).addReg(ReadAgainReg);
9481 BuildMI(BB, dl, TII->get(PPC::BCC))
9482 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
9484 BB->addSuccessor(readMBB);
9485 BB->addSuccessor(sinkMBB);
9486 } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
9487 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
9488 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
9489 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
9490 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
9491 BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
9492 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
9493 BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
9495 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
9496 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
9497 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
9498 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
9499 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
9500 BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
9501 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
9502 BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
9504 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
9505 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
9506 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
9507 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
9508 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
9509 BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
9510 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
9511 BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
9513 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
9514 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
9515 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
9516 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
9517 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
9518 BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
9519 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
9520 BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
9522 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
9523 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
9524 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
9525 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
9526 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
9527 BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
9528 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
9529 BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
9531 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
9532 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
9533 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
9534 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
9535 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
9536 BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
9537 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
9538 BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
9540 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
9541 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
9542 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
9543 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
9544 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
9545 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
9546 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
9547 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
9549 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
9550 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
9551 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
9552 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
9553 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
9554 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
9555 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
9556 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
9558 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
9559 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
9560 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
9561 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
9562 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
9563 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
9564 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
9565 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
9567 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
9568 BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
9569 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
9570 BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
9571 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
9572 BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
9573 else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
9574 BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
9576 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
9577 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
9578 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
9579 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
9580 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
9581 BB = EmitAtomicBinary(MI, BB, 4, 0);
9582 else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
9583 BB = EmitAtomicBinary(MI, BB, 8, 0);
9584 else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
9585 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
9586 (Subtarget.hasPartwordAtomics() &&
9587 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
9588 (Subtarget.hasPartwordAtomics() &&
9589 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
9590 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
9592 auto LoadMnemonic = PPC::LDARX;
9593 auto StoreMnemonic = PPC::STDCX;
9594 switch (MI.getOpcode()) {
9596 llvm_unreachable("Compare and swap of unknown size");
9597 case PPC::ATOMIC_CMP_SWAP_I8:
9598 LoadMnemonic = PPC::LBARX;
9599 StoreMnemonic = PPC::STBCX;
9600 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9602 case PPC::ATOMIC_CMP_SWAP_I16:
9603 LoadMnemonic = PPC::LHARX;
9604 StoreMnemonic = PPC::STHCX;
9605 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9607 case PPC::ATOMIC_CMP_SWAP_I32:
9608 LoadMnemonic = PPC::LWARX;
9609 StoreMnemonic = PPC::STWCX;
9611 case PPC::ATOMIC_CMP_SWAP_I64:
9612 LoadMnemonic = PPC::LDARX;
9613 StoreMnemonic = PPC::STDCX;
9616 unsigned dest = MI.getOperand(0).getReg();
9617 unsigned ptrA = MI.getOperand(1).getReg();
9618 unsigned ptrB = MI.getOperand(2).getReg();
9619 unsigned oldval = MI.getOperand(3).getReg();
9620 unsigned newval = MI.getOperand(4).getReg();
9621 DebugLoc dl = MI.getDebugLoc();
9623 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9624 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9625 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9626 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9627 F->insert(It, loop1MBB);
9628 F->insert(It, loop2MBB);
9629 F->insert(It, midMBB);
9630 F->insert(It, exitMBB);
9631 exitMBB->splice(exitMBB->begin(), BB,
9632 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9633 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9637 // fallthrough --> loopMBB
9638 BB->addSuccessor(loop1MBB);
9641 // l[bhwd]arx dest, ptr
9642 // cmp[wd] dest, oldval
9645 // st[bhwd]cx. newval, ptr
9649 // st[bhwd]cx. dest, ptr
9652 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9653 .addReg(ptrA).addReg(ptrB);
9654 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
9655 .addReg(oldval).addReg(dest);
9656 BuildMI(BB, dl, TII->get(PPC::BCC))
9657 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9658 BB->addSuccessor(loop2MBB);
9659 BB->addSuccessor(midMBB);
9662 BuildMI(BB, dl, TII->get(StoreMnemonic))
9663 .addReg(newval).addReg(ptrA).addReg(ptrB);
9664 BuildMI(BB, dl, TII->get(PPC::BCC))
9665 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9666 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9667 BB->addSuccessor(loop1MBB);
9668 BB->addSuccessor(exitMBB);
9671 BuildMI(BB, dl, TII->get(StoreMnemonic))
9672 .addReg(dest).addReg(ptrA).addReg(ptrB);
9673 BB->addSuccessor(exitMBB);
9678 } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
9679 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
9680 // We must use 64-bit registers for addresses when targeting 64-bit,
9681 // since we're actually doing arithmetic on them. Other registers
9683 bool is64bit = Subtarget.isPPC64();
9684 bool isLittleEndian = Subtarget.isLittleEndian();
9685 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
9687 unsigned dest = MI.getOperand(0).getReg();
9688 unsigned ptrA = MI.getOperand(1).getReg();
9689 unsigned ptrB = MI.getOperand(2).getReg();
9690 unsigned oldval = MI.getOperand(3).getReg();
9691 unsigned newval = MI.getOperand(4).getReg();
9692 DebugLoc dl = MI.getDebugLoc();
9694 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9695 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9696 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9697 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9698 F->insert(It, loop1MBB);
9699 F->insert(It, loop2MBB);
9700 F->insert(It, midMBB);
9701 F->insert(It, exitMBB);
9702 exitMBB->splice(exitMBB->begin(), BB,
9703 std::next(MachineBasicBlock::iterator(MI)), BB->end());
9704 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9706 MachineRegisterInfo &RegInfo = F->getRegInfo();
9707 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9708 : &PPC::GPRCRegClass;
9709 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9710 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9712 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
9713 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
9714 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
9715 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
9716 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
9717 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9718 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9719 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9720 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9721 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9722 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9724 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
9725 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9728 // fallthrough --> loopMBB
9729 BB->addSuccessor(loop1MBB);
9731 // The 4-byte load must be aligned, while a char or short may be
9732 // anywhere in the word. Hence all this nasty bookkeeping code.
9733 // add ptr1, ptrA, ptrB [copy if ptrA==0]
9734 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9735 // xori shift, shift1, 24 [16]
9736 // rlwinm ptr, ptr1, 0, 0, 29
9737 // slw newval2, newval, shift
9738 // slw oldval2, oldval,shift
9739 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9740 // slw mask, mask2, shift
9741 // and newval3, newval2, mask
9742 // and oldval3, oldval2, mask
9744 // lwarx tmpDest, ptr
9745 // and tmp, tmpDest, mask
9746 // cmpw tmp, oldval3
9749 // andc tmp2, tmpDest, mask
9750 // or tmp4, tmp2, newval3
9755 // stwcx. tmpDest, ptr
9757 // srw dest, tmpDest, shift
9758 if (ptrA != ZeroReg) {
9759 Ptr1Reg = RegInfo.createVirtualRegister(RC);
9760 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9761 .addReg(ptrA).addReg(ptrB);
9765 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9766 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9767 if (!isLittleEndian)
9768 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9769 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9771 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9772 .addReg(Ptr1Reg).addImm(0).addImm(61);
9774 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9775 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9776 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
9777 .addReg(newval).addReg(ShiftReg);
9778 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
9779 .addReg(oldval).addReg(ShiftReg);
9781 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9783 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9784 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
9785 .addReg(Mask3Reg).addImm(65535);
9787 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9788 .addReg(Mask2Reg).addReg(ShiftReg);
9789 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
9790 .addReg(NewVal2Reg).addReg(MaskReg);
9791 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
9792 .addReg(OldVal2Reg).addReg(MaskReg);
9795 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9796 .addReg(ZeroReg).addReg(PtrReg);
9797 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
9798 .addReg(TmpDestReg).addReg(MaskReg);
9799 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
9800 .addReg(TmpReg).addReg(OldVal3Reg);
9801 BuildMI(BB, dl, TII->get(PPC::BCC))
9802 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9803 BB->addSuccessor(loop2MBB);
9804 BB->addSuccessor(midMBB);
9807 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
9808 .addReg(TmpDestReg).addReg(MaskReg);
9809 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9810 .addReg(Tmp2Reg).addReg(NewVal3Reg);
9811 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9812 .addReg(ZeroReg).addReg(PtrReg);
9813 BuildMI(BB, dl, TII->get(PPC::BCC))
9814 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9815 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9816 BB->addSuccessor(loop1MBB);
9817 BB->addSuccessor(exitMBB);
9820 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9821 .addReg(ZeroReg).addReg(PtrReg);
9822 BB->addSuccessor(exitMBB);
9827 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9829 } else if (MI.getOpcode() == PPC::FADDrtz) {
9830 // This pseudo performs an FADD with rounding mode temporarily forced
9831 // to round-to-zero. We emit this via custom inserter since the FPSCR
9832 // is not modeled at the SelectionDAG level.
9833 unsigned Dest = MI.getOperand(0).getReg();
9834 unsigned Src1 = MI.getOperand(1).getReg();
9835 unsigned Src2 = MI.getOperand(2).getReg();
9836 DebugLoc dl = MI.getDebugLoc();
9838 MachineRegisterInfo &RegInfo = F->getRegInfo();
9839 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9841 // Save FPSCR value.
9842 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9844 // Set rounding mode to round-to-zero.
9845 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9846 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9848 // Perform addition.
9849 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9851 // Restore FPSCR value.
9852 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9853 } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9854 MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
9855 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9856 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9857 unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9858 MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
9861 bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9862 MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9864 MachineRegisterInfo &RegInfo = F->getRegInfo();
9865 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9866 &PPC::GPRCRegClass :
9867 &PPC::G8RCRegClass);
9869 DebugLoc dl = MI.getDebugLoc();
9870 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
9871 .addReg(MI.getOperand(1).getReg())
9873 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
9874 MI.getOperand(0).getReg())
9875 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
9876 } else if (MI.getOpcode() == PPC::TCHECK_RET) {
9877 DebugLoc Dl = MI.getDebugLoc();
9878 MachineRegisterInfo &RegInfo = F->getRegInfo();
9879 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9880 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
9883 llvm_unreachable("Unexpected instr type to insert");
9886 MI.eraseFromParent(); // The pseudo instruction is gone now.
9890 //===----------------------------------------------------------------------===//
9891 // Target Optimization Hooks
9892 //===----------------------------------------------------------------------===//
9894 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
9895 // For the estimates, convergence is quadratic, so we essentially double the
9896 // number of digits correct after every iteration. For both FRE and FRSQRTE,
9897 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
9898 // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
9899 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
9900 if (VT.getScalarType() == MVT::f64)
9902 return RefinementSteps;
9905 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
9906 int Enabled, int &RefinementSteps,
9907 bool &UseOneConstNR,
9908 bool Reciprocal) const {
9909 EVT VT = Operand.getValueType();
9910 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
9911 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
9912 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9913 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9914 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9915 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9916 if (RefinementSteps == ReciprocalEstimate::Unspecified)
9917 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
9919 UseOneConstNR = true;
9920 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
9925 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
9927 int &RefinementSteps) const {
9928 EVT VT = Operand.getValueType();
9929 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
9930 (VT == MVT::f64 && Subtarget.hasFRE()) ||
9931 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9932 (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9933 (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9934 (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9935 if (RefinementSteps == ReciprocalEstimate::Unspecified)
9936 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
9937 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
9942 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
9943 // Note: This functionality is used only when unsafe-fp-math is enabled, and
9944 // on cores with reciprocal estimates (which are used when unsafe-fp-math is
9945 // enabled for division), this functionality is redundant with the default
9946 // combiner logic (once the division -> reciprocal/multiply transformation
9947 // has taken place). As a result, this matters more for older cores than for
9950 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9951 // reciprocal if there are two or more FDIVs (for embedded cores with only
9952 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
9953 switch (Subtarget.getDarwinDirective()) {
9958 case PPC::DIR_E500mc:
9959 case PPC::DIR_E5500:
9964 // isConsecutiveLSLoc needs to work even if all adds have not yet been
9965 // collapsed, and so we need to look through chains of them.
9966 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
9967 int64_t& Offset, SelectionDAG &DAG) {
9968 if (DAG.isBaseWithConstantOffset(Loc)) {
9969 Base = Loc.getOperand(0);
9970 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
9972 // The base might itself be a base plus an offset, and if so, accumulate
9974 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
9978 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
9979 unsigned Bytes, int Dist,
9980 SelectionDAG &DAG) {
9981 if (VT.getSizeInBits() / 8 != Bytes)
9984 SDValue BaseLoc = Base->getBasePtr();
9985 if (Loc.getOpcode() == ISD::FrameIndex) {
9986 if (BaseLoc.getOpcode() != ISD::FrameIndex)
9988 const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9989 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
9990 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
9991 int FS = MFI.getObjectSize(FI);
9992 int BFS = MFI.getObjectSize(BFI);
9993 if (FS != BFS || FS != (int)Bytes) return false;
9994 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
9997 SDValue Base1 = Loc, Base2 = BaseLoc;
9998 int64_t Offset1 = 0, Offset2 = 0;
9999 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
10000 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
10001 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
10004 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10005 const GlobalValue *GV1 = nullptr;
10006 const GlobalValue *GV2 = nullptr;
10009 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
10010 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
10011 if (isGA1 && isGA2 && GV1 == GV2)
10012 return Offset1 == (Offset2 + Dist*Bytes);
10016 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
10017 // not enforce equality of the chain operands.
10018 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
10019 unsigned Bytes, int Dist,
10020 SelectionDAG &DAG) {
10021 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
10022 EVT VT = LS->getMemoryVT();
10023 SDValue Loc = LS->getBasePtr();
10024 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
10027 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
10029 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10030 default: return false;
10031 case Intrinsic::ppc_qpx_qvlfd:
10032 case Intrinsic::ppc_qpx_qvlfda:
10035 case Intrinsic::ppc_qpx_qvlfs:
10036 case Intrinsic::ppc_qpx_qvlfsa:
10039 case Intrinsic::ppc_qpx_qvlfcd:
10040 case Intrinsic::ppc_qpx_qvlfcda:
10043 case Intrinsic::ppc_qpx_qvlfcs:
10044 case Intrinsic::ppc_qpx_qvlfcsa:
10047 case Intrinsic::ppc_qpx_qvlfiwa:
10048 case Intrinsic::ppc_qpx_qvlfiwz:
10049 case Intrinsic::ppc_altivec_lvx:
10050 case Intrinsic::ppc_altivec_lvxl:
10051 case Intrinsic::ppc_vsx_lxvw4x:
10052 case Intrinsic::ppc_vsx_lxvw4x_be:
10055 case Intrinsic::ppc_vsx_lxvd2x:
10056 case Intrinsic::ppc_vsx_lxvd2x_be:
10059 case Intrinsic::ppc_altivec_lvebx:
10062 case Intrinsic::ppc_altivec_lvehx:
10065 case Intrinsic::ppc_altivec_lvewx:
10070 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
10073 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
10075 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10076 default: return false;
10077 case Intrinsic::ppc_qpx_qvstfd:
10078 case Intrinsic::ppc_qpx_qvstfda:
10081 case Intrinsic::ppc_qpx_qvstfs:
10082 case Intrinsic::ppc_qpx_qvstfsa:
10085 case Intrinsic::ppc_qpx_qvstfcd:
10086 case Intrinsic::ppc_qpx_qvstfcda:
10089 case Intrinsic::ppc_qpx_qvstfcs:
10090 case Intrinsic::ppc_qpx_qvstfcsa:
10093 case Intrinsic::ppc_qpx_qvstfiw:
10094 case Intrinsic::ppc_qpx_qvstfiwa:
10095 case Intrinsic::ppc_altivec_stvx:
10096 case Intrinsic::ppc_altivec_stvxl:
10097 case Intrinsic::ppc_vsx_stxvw4x:
10100 case Intrinsic::ppc_vsx_stxvd2x:
10103 case Intrinsic::ppc_vsx_stxvw4x_be:
10106 case Intrinsic::ppc_vsx_stxvd2x_be:
10109 case Intrinsic::ppc_altivec_stvebx:
10112 case Intrinsic::ppc_altivec_stvehx:
10115 case Intrinsic::ppc_altivec_stvewx:
10120 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
10126 // Return true is there is a nearyby consecutive load to the one provided
10127 // (regardless of alignment). We search up and down the chain, looking though
10128 // token factors and other loads (but nothing else). As a result, a true result
10129 // indicates that it is safe to create a new consecutive load adjacent to the
10131 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
10132 SDValue Chain = LD->getChain();
10133 EVT VT = LD->getMemoryVT();
10135 SmallSet<SDNode *, 16> LoadRoots;
10136 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
10137 SmallSet<SDNode *, 16> Visited;
10139 // First, search up the chain, branching to follow all token-factor operands.
10140 // If we find a consecutive load, then we're done, otherwise, record all
10141 // nodes just above the top-level loads and token factors.
10142 while (!Queue.empty()) {
10143 SDNode *ChainNext = Queue.pop_back_val();
10144 if (!Visited.insert(ChainNext).second)
10147 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
10148 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10151 if (!Visited.count(ChainLD->getChain().getNode()))
10152 Queue.push_back(ChainLD->getChain().getNode());
10153 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
10154 for (const SDUse &O : ChainNext->ops())
10155 if (!Visited.count(O.getNode()))
10156 Queue.push_back(O.getNode());
10158 LoadRoots.insert(ChainNext);
10161 // Second, search down the chain, starting from the top-level nodes recorded
10162 // in the first phase. These top-level nodes are the nodes just above all
10163 // loads and token factors. Starting with their uses, recursively look though
10164 // all loads (just the chain uses) and token factors to find a consecutive
10169 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
10170 IE = LoadRoots.end(); I != IE; ++I) {
10171 Queue.push_back(*I);
10173 while (!Queue.empty()) {
10174 SDNode *LoadRoot = Queue.pop_back_val();
10175 if (!Visited.insert(LoadRoot).second)
10178 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
10179 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10182 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
10183 UE = LoadRoot->use_end(); UI != UE; ++UI)
10184 if (((isa<MemSDNode>(*UI) &&
10185 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
10186 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
10187 Queue.push_back(*UI);
10194 /// This function is called when we have proved that a SETCC node can be replaced
10195 /// by subtraction (and other supporting instructions) so that the result of
10196 /// comparison is kept in a GPR instead of CR. This function is purely for
10197 /// codegen purposes and has some flags to guide the codegen process.
10198 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
10199 bool Swap, SDLoc &DL, SelectionDAG &DAG) {
10200 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10202 // Zero extend the operands to the largest legal integer. Originally, they
10203 // must be of a strictly smaller size.
10204 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
10205 DAG.getConstant(Size, DL, MVT::i32));
10206 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
10207 DAG.getConstant(Size, DL, MVT::i32));
10209 // Swap if needed. Depends on the condition code.
10211 std::swap(Op0, Op1);
10213 // Subtract extended integers.
10214 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
10216 // Move the sign bit to the least significant position and zero out the rest.
10217 // Now the least significant bit carries the result of original comparison.
10218 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
10219 DAG.getConstant(Size - 1, DL, MVT::i32));
10220 auto Final = Shifted;
10222 // Complement the result if needed. Based on the condition code.
10224 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
10225 DAG.getConstant(1, DL, MVT::i64));
10227 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
10230 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
10231 DAGCombinerInfo &DCI) const {
10232 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10234 SelectionDAG &DAG = DCI.DAG;
10237 // Size of integers being compared has a critical role in the following
10238 // analysis, so we prefer to do this when all types are legal.
10239 if (!DCI.isAfterLegalizeVectorOps())
10242 // If all users of SETCC extend its value to a legal integer type
10243 // then we replace SETCC with a subtraction
10244 for (SDNode::use_iterator UI = N->use_begin(),
10245 UE = N->use_end(); UI != UE; ++UI) {
10246 if (UI->getOpcode() != ISD::ZERO_EXTEND)
10250 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10251 auto OpSize = N->getOperand(0).getValueSizeInBits();
10253 unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
10255 if (OpSize < Size) {
10259 return generateEquivalentSub(N, Size, false, false, DL, DAG);
10261 return generateEquivalentSub(N, Size, true, true, DL, DAG);
10263 return generateEquivalentSub(N, Size, false, true, DL, DAG);
10265 return generateEquivalentSub(N, Size, true, false, DL, DAG);
10272 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
10273 DAGCombinerInfo &DCI) const {
10274 SelectionDAG &DAG = DCI.DAG;
10277 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
10278 // If we're tracking CR bits, we need to be careful that we don't have:
10279 // trunc(binary-ops(zext(x), zext(y)))
10281 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
10282 // such that we're unnecessarily moving things into GPRs when it would be
10283 // better to keep them in CR bits.
10285 // Note that trunc here can be an actual i1 trunc, or can be the effective
10286 // truncation that comes from a setcc or select_cc.
10287 if (N->getOpcode() == ISD::TRUNCATE &&
10288 N->getValueType(0) != MVT::i1)
10291 if (N->getOperand(0).getValueType() != MVT::i32 &&
10292 N->getOperand(0).getValueType() != MVT::i64)
10295 if (N->getOpcode() == ISD::SETCC ||
10296 N->getOpcode() == ISD::SELECT_CC) {
10297 // If we're looking at a comparison, then we need to make sure that the
10298 // high bits (all except for the first) don't matter the result.
10300 cast<CondCodeSDNode>(N->getOperand(
10301 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
10302 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
10304 if (ISD::isSignedIntSetCC(CC)) {
10305 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
10306 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
10308 } else if (ISD::isUnsignedIntSetCC(CC)) {
10309 if (!DAG.MaskedValueIsZero(N->getOperand(0),
10310 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
10311 !DAG.MaskedValueIsZero(N->getOperand(1),
10312 APInt::getHighBitsSet(OpBits, OpBits-1)))
10313 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
10316 // This is neither a signed nor an unsigned comparison, just make sure
10317 // that the high bits are equal.
10318 KnownBits Op1Known, Op2Known;
10319 DAG.computeKnownBits(N->getOperand(0), Op1Known);
10320 DAG.computeKnownBits(N->getOperand(1), Op2Known);
10322 // We don't really care about what is known about the first bit (if
10323 // anything), so clear it in all masks prior to comparing them.
10324 Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
10325 Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
10327 if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
10332 // We now know that the higher-order bits are irrelevant, we just need to
10333 // make sure that all of the intermediate operations are bit operations, and
10334 // all inputs are extensions.
10335 if (N->getOperand(0).getOpcode() != ISD::AND &&
10336 N->getOperand(0).getOpcode() != ISD::OR &&
10337 N->getOperand(0).getOpcode() != ISD::XOR &&
10338 N->getOperand(0).getOpcode() != ISD::SELECT &&
10339 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
10340 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
10341 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
10342 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
10343 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
10346 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
10347 N->getOperand(1).getOpcode() != ISD::AND &&
10348 N->getOperand(1).getOpcode() != ISD::OR &&
10349 N->getOperand(1).getOpcode() != ISD::XOR &&
10350 N->getOperand(1).getOpcode() != ISD::SELECT &&
10351 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
10352 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
10353 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
10354 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
10355 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
10358 SmallVector<SDValue, 4> Inputs;
10359 SmallVector<SDValue, 8> BinOps, PromOps;
10360 SmallPtrSet<SDNode *, 16> Visited;
10362 for (unsigned i = 0; i < 2; ++i) {
10363 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10364 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10365 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10366 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10367 isa<ConstantSDNode>(N->getOperand(i)))
10368 Inputs.push_back(N->getOperand(i));
10370 BinOps.push_back(N->getOperand(i));
10372 if (N->getOpcode() == ISD::TRUNCATE)
10376 // Visit all inputs, collect all binary operations (and, or, xor and
10377 // select) that are all fed by extensions.
10378 while (!BinOps.empty()) {
10379 SDValue BinOp = BinOps.back();
10382 if (!Visited.insert(BinOp.getNode()).second)
10385 PromOps.push_back(BinOp);
10387 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10388 // The condition of the select is not promoted.
10389 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10391 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10394 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10395 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10396 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10397 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10398 isa<ConstantSDNode>(BinOp.getOperand(i))) {
10399 Inputs.push_back(BinOp.getOperand(i));
10400 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10401 BinOp.getOperand(i).getOpcode() == ISD::OR ||
10402 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10403 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10404 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
10405 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10406 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10407 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10408 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
10409 BinOps.push_back(BinOp.getOperand(i));
10411 // We have an input that is not an extension or another binary
10412 // operation; we'll abort this transformation.
10418 // Make sure that this is a self-contained cluster of operations (which
10419 // is not quite the same thing as saying that everything has only one
10421 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10422 if (isa<ConstantSDNode>(Inputs[i]))
10425 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10426 UE = Inputs[i].getNode()->use_end();
10428 SDNode *User = *UI;
10429 if (User != N && !Visited.count(User))
10432 // Make sure that we're not going to promote the non-output-value
10433 // operand(s) or SELECT or SELECT_CC.
10434 // FIXME: Although we could sometimes handle this, and it does occur in
10435 // practice that one of the condition inputs to the select is also one of
10436 // the outputs, we currently can't deal with this.
10437 if (User->getOpcode() == ISD::SELECT) {
10438 if (User->getOperand(0) == Inputs[i])
10440 } else if (User->getOpcode() == ISD::SELECT_CC) {
10441 if (User->getOperand(0) == Inputs[i] ||
10442 User->getOperand(1) == Inputs[i])
10448 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10449 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10450 UE = PromOps[i].getNode()->use_end();
10452 SDNode *User = *UI;
10453 if (User != N && !Visited.count(User))
10456 // Make sure that we're not going to promote the non-output-value
10457 // operand(s) or SELECT or SELECT_CC.
10458 // FIXME: Although we could sometimes handle this, and it does occur in
10459 // practice that one of the condition inputs to the select is also one of
10460 // the outputs, we currently can't deal with this.
10461 if (User->getOpcode() == ISD::SELECT) {
10462 if (User->getOperand(0) == PromOps[i])
10464 } else if (User->getOpcode() == ISD::SELECT_CC) {
10465 if (User->getOperand(0) == PromOps[i] ||
10466 User->getOperand(1) == PromOps[i])
10472 // Replace all inputs with the extension operand.
10473 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10474 // Constants may have users outside the cluster of to-be-promoted nodes,
10475 // and so we need to replace those as we do the promotions.
10476 if (isa<ConstantSDNode>(Inputs[i]))
10479 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
10482 std::list<HandleSDNode> PromOpHandles;
10483 for (auto &PromOp : PromOps)
10484 PromOpHandles.emplace_back(PromOp);
10486 // Replace all operations (these are all the same, but have a different
10487 // (i1) return type). DAG.getNode will validate that the types of
10488 // a binary operator match, so go through the list in reverse so that
10489 // we've likely promoted both operands first. Any intermediate truncations or
10490 // extensions disappear.
10491 while (!PromOpHandles.empty()) {
10492 SDValue PromOp = PromOpHandles.back().getValue();
10493 PromOpHandles.pop_back();
10495 if (PromOp.getOpcode() == ISD::TRUNCATE ||
10496 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
10497 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
10498 PromOp.getOpcode() == ISD::ANY_EXTEND) {
10499 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
10500 PromOp.getOperand(0).getValueType() != MVT::i1) {
10501 // The operand is not yet ready (see comment below).
10502 PromOpHandles.emplace_front(PromOp);
10506 SDValue RepValue = PromOp.getOperand(0);
10507 if (isa<ConstantSDNode>(RepValue))
10508 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
10510 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
10515 switch (PromOp.getOpcode()) {
10516 default: C = 0; break;
10517 case ISD::SELECT: C = 1; break;
10518 case ISD::SELECT_CC: C = 2; break;
10521 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10522 PromOp.getOperand(C).getValueType() != MVT::i1) ||
10523 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10524 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
10525 // The to-be-promoted operands of this node have not yet been
10526 // promoted (this should be rare because we're going through the
10527 // list backward, but if one of the operands has several users in
10528 // this cluster of to-be-promoted nodes, it is possible).
10529 PromOpHandles.emplace_front(PromOp);
10533 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10534 PromOp.getNode()->op_end());
10536 // If there are any constant inputs, make sure they're replaced now.
10537 for (unsigned i = 0; i < 2; ++i)
10538 if (isa<ConstantSDNode>(Ops[C+i]))
10539 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
10541 DAG.ReplaceAllUsesOfValueWith(PromOp,
10542 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
10545 // Now we're left with the initial truncation itself.
10546 if (N->getOpcode() == ISD::TRUNCATE)
10547 return N->getOperand(0);
10549 // Otherwise, this is a comparison. The operands to be compared have just
10550 // changed type (to i1), but everything else is the same.
10551 return SDValue(N, 0);
10554 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
10555 DAGCombinerInfo &DCI) const {
10556 SelectionDAG &DAG = DCI.DAG;
10559 // If we're tracking CR bits, we need to be careful that we don't have:
10560 // zext(binary-ops(trunc(x), trunc(y)))
10562 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
10563 // such that we're unnecessarily moving things into CR bits that can more
10564 // efficiently stay in GPRs. Note that if we're not certain that the high
10565 // bits are set as required by the final extension, we still may need to do
10566 // some masking to get the proper behavior.
10568 // This same functionality is important on PPC64 when dealing with
10569 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
10570 // the return values of functions. Because it is so similar, it is handled
10573 if (N->getValueType(0) != MVT::i32 &&
10574 N->getValueType(0) != MVT::i64)
10577 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
10578 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
10581 if (N->getOperand(0).getOpcode() != ISD::AND &&
10582 N->getOperand(0).getOpcode() != ISD::OR &&
10583 N->getOperand(0).getOpcode() != ISD::XOR &&
10584 N->getOperand(0).getOpcode() != ISD::SELECT &&
10585 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
10588 SmallVector<SDValue, 4> Inputs;
10589 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
10590 SmallPtrSet<SDNode *, 16> Visited;
10592 // Visit all inputs, collect all binary operations (and, or, xor and
10593 // select) that are all fed by truncations.
10594 while (!BinOps.empty()) {
10595 SDValue BinOp = BinOps.back();
10598 if (!Visited.insert(BinOp.getNode()).second)
10601 PromOps.push_back(BinOp);
10603 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10604 // The condition of the select is not promoted.
10605 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10607 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10610 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10611 isa<ConstantSDNode>(BinOp.getOperand(i))) {
10612 Inputs.push_back(BinOp.getOperand(i));
10613 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10614 BinOp.getOperand(i).getOpcode() == ISD::OR ||
10615 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10616 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10617 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
10618 BinOps.push_back(BinOp.getOperand(i));
10620 // We have an input that is not a truncation or another binary
10621 // operation; we'll abort this transformation.
10627 // The operands of a select that must be truncated when the select is
10628 // promoted because the operand is actually part of the to-be-promoted set.
10629 DenseMap<SDNode *, EVT> SelectTruncOp[2];
10631 // Make sure that this is a self-contained cluster of operations (which
10632 // is not quite the same thing as saying that everything has only one
10634 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10635 if (isa<ConstantSDNode>(Inputs[i]))
10638 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10639 UE = Inputs[i].getNode()->use_end();
10641 SDNode *User = *UI;
10642 if (User != N && !Visited.count(User))
10645 // If we're going to promote the non-output-value operand(s) or SELECT or
10646 // SELECT_CC, record them for truncation.
10647 if (User->getOpcode() == ISD::SELECT) {
10648 if (User->getOperand(0) == Inputs[i])
10649 SelectTruncOp[0].insert(std::make_pair(User,
10650 User->getOperand(0).getValueType()));
10651 } else if (User->getOpcode() == ISD::SELECT_CC) {
10652 if (User->getOperand(0) == Inputs[i])
10653 SelectTruncOp[0].insert(std::make_pair(User,
10654 User->getOperand(0).getValueType()));
10655 if (User->getOperand(1) == Inputs[i])
10656 SelectTruncOp[1].insert(std::make_pair(User,
10657 User->getOperand(1).getValueType()));
10662 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10663 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10664 UE = PromOps[i].getNode()->use_end();
10666 SDNode *User = *UI;
10667 if (User != N && !Visited.count(User))
10670 // If we're going to promote the non-output-value operand(s) or SELECT or
10671 // SELECT_CC, record them for truncation.
10672 if (User->getOpcode() == ISD::SELECT) {
10673 if (User->getOperand(0) == PromOps[i])
10674 SelectTruncOp[0].insert(std::make_pair(User,
10675 User->getOperand(0).getValueType()));
10676 } else if (User->getOpcode() == ISD::SELECT_CC) {
10677 if (User->getOperand(0) == PromOps[i])
10678 SelectTruncOp[0].insert(std::make_pair(User,
10679 User->getOperand(0).getValueType()));
10680 if (User->getOperand(1) == PromOps[i])
10681 SelectTruncOp[1].insert(std::make_pair(User,
10682 User->getOperand(1).getValueType()));
10687 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
10688 bool ReallyNeedsExt = false;
10689 if (N->getOpcode() != ISD::ANY_EXTEND) {
10690 // If all of the inputs are not already sign/zero extended, then
10691 // we'll still need to do that at the end.
10692 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10693 if (isa<ConstantSDNode>(Inputs[i]))
10697 Inputs[i].getOperand(0).getValueSizeInBits();
10698 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
10700 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
10701 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
10702 APInt::getHighBitsSet(OpBits,
10703 OpBits-PromBits))) ||
10704 (N->getOpcode() == ISD::SIGN_EXTEND &&
10705 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
10706 (OpBits-(PromBits-1)))) {
10707 ReallyNeedsExt = true;
10713 // Replace all inputs, either with the truncation operand, or a
10714 // truncation or extension to the final output type.
10715 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10716 // Constant inputs need to be replaced with the to-be-promoted nodes that
10717 // use them because they might have users outside of the cluster of
10719 if (isa<ConstantSDNode>(Inputs[i]))
10722 SDValue InSrc = Inputs[i].getOperand(0);
10723 if (Inputs[i].getValueType() == N->getValueType(0))
10724 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
10725 else if (N->getOpcode() == ISD::SIGN_EXTEND)
10726 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10727 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
10728 else if (N->getOpcode() == ISD::ZERO_EXTEND)
10729 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10730 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
10732 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10733 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
10736 std::list<HandleSDNode> PromOpHandles;
10737 for (auto &PromOp : PromOps)
10738 PromOpHandles.emplace_back(PromOp);
10740 // Replace all operations (these are all the same, but have a different
10741 // (promoted) return type). DAG.getNode will validate that the types of
10742 // a binary operator match, so go through the list in reverse so that
10743 // we've likely promoted both operands first.
10744 while (!PromOpHandles.empty()) {
10745 SDValue PromOp = PromOpHandles.back().getValue();
10746 PromOpHandles.pop_back();
10749 switch (PromOp.getOpcode()) {
10750 default: C = 0; break;
10751 case ISD::SELECT: C = 1; break;
10752 case ISD::SELECT_CC: C = 2; break;
10755 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10756 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
10757 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10758 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
10759 // The to-be-promoted operands of this node have not yet been
10760 // promoted (this should be rare because we're going through the
10761 // list backward, but if one of the operands has several users in
10762 // this cluster of to-be-promoted nodes, it is possible).
10763 PromOpHandles.emplace_front(PromOp);
10767 // For SELECT and SELECT_CC nodes, we do a similar check for any
10768 // to-be-promoted comparison inputs.
10769 if (PromOp.getOpcode() == ISD::SELECT ||
10770 PromOp.getOpcode() == ISD::SELECT_CC) {
10771 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
10772 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
10773 (SelectTruncOp[1].count(PromOp.getNode()) &&
10774 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
10775 PromOpHandles.emplace_front(PromOp);
10780 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10781 PromOp.getNode()->op_end());
10783 // If this node has constant inputs, then they'll need to be promoted here.
10784 for (unsigned i = 0; i < 2; ++i) {
10785 if (!isa<ConstantSDNode>(Ops[C+i]))
10787 if (Ops[C+i].getValueType() == N->getValueType(0))
10790 if (N->getOpcode() == ISD::SIGN_EXTEND)
10791 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10792 else if (N->getOpcode() == ISD::ZERO_EXTEND)
10793 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10795 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10798 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
10799 // truncate them again to the original value type.
10800 if (PromOp.getOpcode() == ISD::SELECT ||
10801 PromOp.getOpcode() == ISD::SELECT_CC) {
10802 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
10803 if (SI0 != SelectTruncOp[0].end())
10804 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
10805 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
10806 if (SI1 != SelectTruncOp[1].end())
10807 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
10810 DAG.ReplaceAllUsesOfValueWith(PromOp,
10811 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
10814 // Now we're left with the initial extension itself.
10815 if (!ReallyNeedsExt)
10816 return N->getOperand(0);
10818 // To zero extend, just mask off everything except for the first bit (in the
10820 if (N->getOpcode() == ISD::ZERO_EXTEND)
10821 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
10822 DAG.getConstant(APInt::getLowBitsSet(
10823 N->getValueSizeInBits(0), PromBits),
10824 dl, N->getValueType(0)));
10826 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
10827 "Invalid extension type");
10828 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
10830 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
10831 return DAG.getNode(
10832 ISD::SRA, dl, N->getValueType(0),
10833 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
10837 /// \brief Reduces the number of fp-to-int conversion when building a vector.
10839 /// If this vector is built out of floating to integer conversions,
10840 /// transform it to a vector built out of floating point values followed by a
10841 /// single floating to integer conversion of the vector.
10842 /// Namely (build_vector (fptosi $A), (fptosi $B), ...)
10843 /// becomes (fptosi (build_vector ($A, $B, ...)))
10844 SDValue PPCTargetLowering::
10845 combineElementTruncationToVectorTruncation(SDNode *N,
10846 DAGCombinerInfo &DCI) const {
10847 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10848 "Should be called with a BUILD_VECTOR node");
10850 SelectionDAG &DAG = DCI.DAG;
10853 SDValue FirstInput = N->getOperand(0);
10854 assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
10855 "The input operand must be an fp-to-int conversion.");
10857 // This combine happens after legalization so the fp_to_[su]i nodes are
10858 // already converted to PPCSISD nodes.
10859 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
10860 if (FirstConversion == PPCISD::FCTIDZ ||
10861 FirstConversion == PPCISD::FCTIDUZ ||
10862 FirstConversion == PPCISD::FCTIWZ ||
10863 FirstConversion == PPCISD::FCTIWUZ) {
10864 bool IsSplat = true;
10865 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
10866 FirstConversion == PPCISD::FCTIWUZ;
10867 EVT SrcVT = FirstInput.getOperand(0).getValueType();
10868 SmallVector<SDValue, 4> Ops;
10869 EVT TargetVT = N->getValueType(0);
10870 for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
10871 if (N->getOperand(i).getOpcode() != PPCISD::MFVSR)
10873 unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode();
10874 if (NextConversion != FirstConversion)
10876 if (N->getOperand(i) != FirstInput)
10880 // If this is a splat, we leave it as-is since there will be only a single
10881 // fp-to-int conversion followed by a splat of the integer. This is better
10882 // for 32-bit and smaller ints and neutral for 64-bit ints.
10886 // Now that we know we have the right type of node, get its operands
10887 for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
10888 SDValue In = N->getOperand(i).getOperand(0);
10889 // For 32-bit values, we need to add an FP_ROUND node.
10892 Ops.push_back(DAG.getUNDEF(SrcVT));
10894 SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
10895 MVT::f32, In.getOperand(0),
10896 DAG.getIntPtrConstant(1, dl));
10897 Ops.push_back(Trunc);
10900 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
10904 if (FirstConversion == PPCISD::FCTIDZ ||
10905 FirstConversion == PPCISD::FCTIWZ)
10906 Opcode = ISD::FP_TO_SINT;
10908 Opcode = ISD::FP_TO_UINT;
10910 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
10911 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
10912 return DAG.getNode(Opcode, dl, TargetVT, BV);
10917 /// \brief Reduce the number of loads when building a vector.
10919 /// Building a vector out of multiple loads can be converted to a load
10920 /// of the vector type if the loads are consecutive. If the loads are
10921 /// consecutive but in descending order, a shuffle is added at the end
10922 /// to reorder the vector.
10923 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
10924 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10925 "Should be called with a BUILD_VECTOR node");
10928 bool InputsAreConsecutiveLoads = true;
10929 bool InputsAreReverseConsecutive = true;
10930 unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8;
10931 SDValue FirstInput = N->getOperand(0);
10932 bool IsRoundOfExtLoad = false;
10934 if (FirstInput.getOpcode() == ISD::FP_ROUND &&
10935 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
10936 LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
10937 IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
10939 // Not a build vector of (possibly fp_rounded) loads.
10940 if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD)
10943 for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
10944 // If any inputs are fp_round(extload), they all must be.
10945 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
10948 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
10950 if (NextInput.getOpcode() != ISD::LOAD)
10953 SDValue PreviousInput =
10954 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
10955 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
10956 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
10958 // If any inputs are fp_round(extload), they all must be.
10959 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
10962 if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
10963 InputsAreConsecutiveLoads = false;
10964 if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
10965 InputsAreReverseConsecutive = false;
10967 // Exit early if the loads are neither consecutive nor reverse consecutive.
10968 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
10972 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
10973 "The loads cannot be both consecutive and reverse consecutive.");
10975 SDValue FirstLoadOp =
10976 IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
10977 SDValue LastLoadOp =
10978 IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
10979 N->getOperand(N->getNumOperands()-1);
10981 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
10982 LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
10983 if (InputsAreConsecutiveLoads) {
10984 assert(LD1 && "Input needs to be a LoadSDNode.");
10985 return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
10986 LD1->getBasePtr(), LD1->getPointerInfo(),
10987 LD1->getAlignment());
10989 if (InputsAreReverseConsecutive) {
10990 assert(LDL && "Input needs to be a LoadSDNode.");
10991 SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
10992 LDL->getBasePtr(), LDL->getPointerInfo(),
10993 LDL->getAlignment());
10994 SmallVector<int, 16> Ops;
10995 for (int i = N->getNumOperands() - 1; i >= 0; i--)
10998 return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
10999 DAG.getUNDEF(N->getValueType(0)), Ops);
11004 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
11005 DAGCombinerInfo &DCI) const {
11006 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11007 "Should be called with a BUILD_VECTOR node");
11009 SelectionDAG &DAG = DCI.DAG;
11012 if (!Subtarget.hasVSX())
11015 // The target independent DAG combiner will leave a build_vector of
11016 // float-to-int conversions intact. We can generate MUCH better code for
11017 // a float-to-int conversion of a vector of floats.
11018 SDValue FirstInput = N->getOperand(0);
11019 if (FirstInput.getOpcode() == PPCISD::MFVSR) {
11020 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
11025 // If we're building a vector out of consecutive loads, just load that
11027 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
11031 if (N->getValueType(0) != MVT::v2f64)
11035 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
11036 if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
11037 FirstInput.getOpcode() != ISD::UINT_TO_FP)
11039 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
11040 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
11042 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
11045 SDValue Ext1 = FirstInput.getOperand(0);
11046 SDValue Ext2 = N->getOperand(1).getOperand(0);
11047 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11048 Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11051 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
11052 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
11053 if (!Ext1Op || !Ext2Op)
11055 if (Ext1.getValueType() != MVT::i32 ||
11056 Ext2.getValueType() != MVT::i32)
11057 if (Ext1.getOperand(0) != Ext2.getOperand(0))
11060 int FirstElem = Ext1Op->getZExtValue();
11061 int SecondElem = Ext2Op->getZExtValue();
11063 if (FirstElem == 0 && SecondElem == 1)
11064 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
11065 else if (FirstElem == 2 && SecondElem == 3)
11066 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
11070 SDValue SrcVec = Ext1.getOperand(0);
11071 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
11072 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
11073 return DAG.getNode(NodeType, dl, MVT::v2f64,
11074 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
11077 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
11078 DAGCombinerInfo &DCI) const {
11079 assert((N->getOpcode() == ISD::SINT_TO_FP ||
11080 N->getOpcode() == ISD::UINT_TO_FP) &&
11081 "Need an int -> FP conversion node here");
11083 if (useSoftFloat() || !Subtarget.has64BitSupport())
11086 SelectionDAG &DAG = DCI.DAG;
11090 SDValue FirstOperand(Op.getOperand(0));
11091 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
11092 (FirstOperand.getValueType() == MVT::i8 ||
11093 FirstOperand.getValueType() == MVT::i16);
11094 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
11095 bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
11096 bool DstDouble = Op.getValueType() == MVT::f64;
11097 unsigned ConvOp = Signed ?
11098 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) :
11099 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
11100 SDValue WidthConst =
11101 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
11103 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
11104 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
11105 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
11106 DAG.getVTList(MVT::f64, MVT::Other),
11107 Ops, MVT::i8, LDN->getMemOperand());
11109 // For signed conversion, we need to sign-extend the value in the VSR
11111 SDValue ExtOps[] = { Ld, WidthConst };
11112 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
11113 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
11115 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
11118 // Don't handle ppc_fp128 here or i1 conversions.
11119 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
11121 if (Op.getOperand(0).getValueType() == MVT::i1)
11124 // For i32 intermediate values, unfortunately, the conversion functions
11125 // leave the upper 32 bits of the value are undefined. Within the set of
11126 // scalar instructions, we have no method for zero- or sign-extending the
11127 // value. Thus, we cannot handle i32 intermediate values here.
11128 if (Op.getOperand(0).getValueType() == MVT::i32)
11131 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
11132 "UINT_TO_FP is supported only with FPCVT");
11134 // If we have FCFIDS, then use it when converting to single-precision.
11135 // Otherwise, convert to double-precision and then round.
11136 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11137 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
11139 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
11141 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11145 // If we're converting from a float, to an int, and back to a float again,
11146 // then we don't need the store/load pair at all.
11147 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
11148 Subtarget.hasFPCVT()) ||
11149 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
11150 SDValue Src = Op.getOperand(0).getOperand(0);
11151 if (Src.getValueType() == MVT::f32) {
11152 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
11153 DCI.AddToWorklist(Src.getNode());
11154 } else if (Src.getValueType() != MVT::f64) {
11155 // Make sure that we don't pick up a ppc_fp128 source value.
11160 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
11163 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
11164 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
11166 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
11167 FP = DAG.getNode(ISD::FP_ROUND, dl,
11168 MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
11169 DCI.AddToWorklist(FP.getNode());
11178 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
11179 // builtins) into loads with swaps.
11180 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
11181 DAGCombinerInfo &DCI) const {
11182 SelectionDAG &DAG = DCI.DAG;
11186 MachineMemOperand *MMO;
11188 switch (N->getOpcode()) {
11190 llvm_unreachable("Unexpected opcode for little endian VSX load");
11192 LoadSDNode *LD = cast<LoadSDNode>(N);
11193 Chain = LD->getChain();
11194 Base = LD->getBasePtr();
11195 MMO = LD->getMemOperand();
11196 // If the MMO suggests this isn't a load of a full vector, leave
11197 // things alone. For a built-in, we have to make the change for
11198 // correctness, so if there is a size problem that will be a bug.
11199 if (MMO->getSize() < 16)
11203 case ISD::INTRINSIC_W_CHAIN: {
11204 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
11205 Chain = Intrin->getChain();
11206 // Similarly to the store case below, Intrin->getBasePtr() doesn't get
11207 // us what we want. Get operand 2 instead.
11208 Base = Intrin->getOperand(2);
11209 MMO = Intrin->getMemOperand();
11214 MVT VecTy = N->getValueType(0).getSimpleVT();
11216 // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
11217 // aligned and the type is a vector with elements up to 4 bytes
11218 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
11219 && VecTy.getScalarSizeInBits() <= 32 ) {
11223 SDValue LoadOps[] = { Chain, Base };
11224 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
11225 DAG.getVTList(MVT::v2f64, MVT::Other),
11226 LoadOps, MVT::v2f64, MMO);
11228 DCI.AddToWorklist(Load.getNode());
11229 Chain = Load.getValue(1);
11230 SDValue Swap = DAG.getNode(
11231 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
11232 DCI.AddToWorklist(Swap.getNode());
11234 // Add a bitcast if the resulting load type doesn't match v2f64.
11235 if (VecTy != MVT::v2f64) {
11236 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
11237 DCI.AddToWorklist(N.getNode());
11238 // Package {bitcast value, swap's chain} to match Load's shape.
11239 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
11240 N, Swap.getValue(1));
11246 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
11247 // builtins) into stores with swaps.
11248 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
11249 DAGCombinerInfo &DCI) const {
11250 SelectionDAG &DAG = DCI.DAG;
11255 MachineMemOperand *MMO;
11257 switch (N->getOpcode()) {
11259 llvm_unreachable("Unexpected opcode for little endian VSX store");
11261 StoreSDNode *ST = cast<StoreSDNode>(N);
11262 Chain = ST->getChain();
11263 Base = ST->getBasePtr();
11264 MMO = ST->getMemOperand();
11266 // If the MMO suggests this isn't a store of a full vector, leave
11267 // things alone. For a built-in, we have to make the change for
11268 // correctness, so if there is a size problem that will be a bug.
11269 if (MMO->getSize() < 16)
11273 case ISD::INTRINSIC_VOID: {
11274 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
11275 Chain = Intrin->getChain();
11276 // Intrin->getBasePtr() oddly does not get what we want.
11277 Base = Intrin->getOperand(3);
11278 MMO = Intrin->getMemOperand();
11284 SDValue Src = N->getOperand(SrcOpnd);
11285 MVT VecTy = Src.getValueType().getSimpleVT();
11287 // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
11288 // aligned and the type is a vector with elements up to 4 bytes
11289 if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
11290 && VecTy.getScalarSizeInBits() <= 32 ) {
11294 // All stores are done as v2f64 and possible bit cast.
11295 if (VecTy != MVT::v2f64) {
11296 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
11297 DCI.AddToWorklist(Src.getNode());
11300 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
11301 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
11302 DCI.AddToWorklist(Swap.getNode());
11303 Chain = Swap.getValue(1);
11304 SDValue StoreOps[] = { Chain, Swap, Base };
11305 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
11306 DAG.getVTList(MVT::Other),
11307 StoreOps, VecTy, MMO);
11308 DCI.AddToWorklist(Store.getNode());
11312 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
11313 DAGCombinerInfo &DCI) const {
11314 SelectionDAG &DAG = DCI.DAG;
11316 switch (N->getOpcode()) {
11319 return combineSHL(N, DCI);
11321 return combineSRA(N, DCI);
11323 return combineSRL(N, DCI);
11325 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
11326 return N->getOperand(0);
11329 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
11330 return N->getOperand(0);
11333 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11334 if (C->isNullValue() || // 0 >>s V -> 0.
11335 C->isAllOnesValue()) // -1 >>s V -> -1.
11336 return N->getOperand(0);
11339 case ISD::SIGN_EXTEND:
11340 case ISD::ZERO_EXTEND:
11341 case ISD::ANY_EXTEND:
11342 return DAGCombineExtBoolTrunc(N, DCI);
11343 case ISD::TRUNCATE:
11345 case ISD::SELECT_CC:
11346 return DAGCombineTruncBoolExt(N, DCI);
11347 case ISD::SINT_TO_FP:
11348 case ISD::UINT_TO_FP:
11349 return combineFPToIntToFP(N, DCI);
11351 EVT Op1VT = N->getOperand(1).getValueType();
11352 bool ValidTypeForStoreFltAsInt = (Op1VT == MVT::i32) ||
11353 (Subtarget.hasP9Vector() && (Op1VT == MVT::i8 || Op1VT == MVT::i16));
11355 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
11356 if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
11357 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
11358 ValidTypeForStoreFltAsInt &&
11359 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
11360 SDValue Val = N->getOperand(1).getOperand(0);
11361 if (Val.getValueType() == MVT::f32) {
11362 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
11363 DCI.AddToWorklist(Val.getNode());
11365 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
11366 DCI.AddToWorklist(Val.getNode());
11368 if (Op1VT == MVT::i32) {
11370 N->getOperand(0), Val, N->getOperand(2),
11371 DAG.getValueType(N->getOperand(1).getValueType())
11374 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
11375 DAG.getVTList(MVT::Other), Ops,
11376 cast<StoreSDNode>(N)->getMemoryVT(),
11377 cast<StoreSDNode>(N)->getMemOperand());
11379 unsigned WidthInBytes =
11380 N->getOperand(1).getValueType() == MVT::i8 ? 1 : 2;
11381 SDValue WidthConst = DAG.getIntPtrConstant(WidthInBytes, dl, false);
11384 N->getOperand(0), Val, N->getOperand(2), WidthConst,
11385 DAG.getValueType(N->getOperand(1).getValueType())
11387 Val = DAG.getMemIntrinsicNode(PPCISD::STXSIX, dl,
11388 DAG.getVTList(MVT::Other), Ops,
11389 cast<StoreSDNode>(N)->getMemoryVT(),
11390 cast<StoreSDNode>(N)->getMemOperand());
11393 DCI.AddToWorklist(Val.getNode());
11397 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
11398 if (cast<StoreSDNode>(N)->isUnindexed() &&
11399 N->getOperand(1).getOpcode() == ISD::BSWAP &&
11400 N->getOperand(1).getNode()->hasOneUse() &&
11401 (N->getOperand(1).getValueType() == MVT::i32 ||
11402 N->getOperand(1).getValueType() == MVT::i16 ||
11403 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11404 N->getOperand(1).getValueType() == MVT::i64))) {
11405 SDValue BSwapOp = N->getOperand(1).getOperand(0);
11406 // Do an any-extend to 32-bits if this is a half-word input.
11407 if (BSwapOp.getValueType() == MVT::i16)
11408 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
11410 // If the type of BSWAP operand is wider than stored memory width
11411 // it need to be shifted to the right side before STBRX.
11412 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
11413 if (Op1VT.bitsGT(mVT)) {
11414 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
11415 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
11416 DAG.getConstant(Shift, dl, MVT::i32));
11417 // Need to truncate if this is a bswap of i64 stored as i32/i16.
11418 if (Op1VT == MVT::i64)
11419 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
11423 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
11426 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
11427 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
11428 cast<StoreSDNode>(N)->getMemOperand());
11431 // For little endian, VSX stores require generating xxswapd/lxvd2x.
11432 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
11433 EVT VT = N->getOperand(1).getValueType();
11434 if (VT.isSimple()) {
11435 MVT StoreVT = VT.getSimpleVT();
11436 if (Subtarget.needsSwapsForVSXMemOps() &&
11437 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
11438 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
11439 return expandVSXStoreForLE(N, DCI);
11444 LoadSDNode *LD = cast<LoadSDNode>(N);
11445 EVT VT = LD->getValueType(0);
11447 // For little endian, VSX loads require generating lxvd2x/xxswapd.
11448 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
11449 if (VT.isSimple()) {
11450 MVT LoadVT = VT.getSimpleVT();
11451 if (Subtarget.needsSwapsForVSXMemOps() &&
11452 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
11453 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
11454 return expandVSXLoadForLE(N, DCI);
11457 // We sometimes end up with a 64-bit integer load, from which we extract
11458 // two single-precision floating-point numbers. This happens with
11459 // std::complex<float>, and other similar structures, because of the way we
11460 // canonicalize structure copies. However, if we lack direct moves,
11461 // then the final bitcasts from the extracted integer values to the
11462 // floating-point numbers turn into store/load pairs. Even with direct moves,
11463 // just loading the two floating-point numbers is likely better.
11464 auto ReplaceTwoFloatLoad = [&]() {
11465 if (VT != MVT::i64)
11468 if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
11472 // We're looking for a sequence like this:
11473 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
11474 // t16: i64 = srl t13, Constant:i32<32>
11475 // t17: i32 = truncate t16
11476 // t18: f32 = bitcast t17
11477 // t19: i32 = truncate t13
11478 // t20: f32 = bitcast t19
11480 if (!LD->hasNUsesOfValue(2, 0))
11483 auto UI = LD->use_begin();
11484 while (UI.getUse().getResNo() != 0) ++UI;
11485 SDNode *Trunc = *UI++;
11486 while (UI.getUse().getResNo() != 0) ++UI;
11487 SDNode *RightShift = *UI;
11488 if (Trunc->getOpcode() != ISD::TRUNCATE)
11489 std::swap(Trunc, RightShift);
11491 if (Trunc->getOpcode() != ISD::TRUNCATE ||
11492 Trunc->getValueType(0) != MVT::i32 ||
11493 !Trunc->hasOneUse())
11495 if (RightShift->getOpcode() != ISD::SRL ||
11496 !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
11497 RightShift->getConstantOperandVal(1) != 32 ||
11498 !RightShift->hasOneUse())
11501 SDNode *Trunc2 = *RightShift->use_begin();
11502 if (Trunc2->getOpcode() != ISD::TRUNCATE ||
11503 Trunc2->getValueType(0) != MVT::i32 ||
11504 !Trunc2->hasOneUse())
11507 SDNode *Bitcast = *Trunc->use_begin();
11508 SDNode *Bitcast2 = *Trunc2->use_begin();
11510 if (Bitcast->getOpcode() != ISD::BITCAST ||
11511 Bitcast->getValueType(0) != MVT::f32)
11513 if (Bitcast2->getOpcode() != ISD::BITCAST ||
11514 Bitcast2->getValueType(0) != MVT::f32)
11517 if (Subtarget.isLittleEndian())
11518 std::swap(Bitcast, Bitcast2);
11520 // Bitcast has the second float (in memory-layout order) and Bitcast2
11521 // has the first one.
11523 SDValue BasePtr = LD->getBasePtr();
11524 if (LD->isIndexed()) {
11525 assert(LD->getAddressingMode() == ISD::PRE_INC &&
11526 "Non-pre-inc AM on PPC?");
11528 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
11533 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
11534 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
11535 LD->getPointerInfo(), LD->getAlignment(),
11536 MMOFlags, LD->getAAInfo());
11538 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
11539 BasePtr, DAG.getIntPtrConstant(4, dl));
11540 SDValue FloatLoad2 = DAG.getLoad(
11541 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
11542 LD->getPointerInfo().getWithOffset(4),
11543 MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
11545 if (LD->isIndexed()) {
11546 // Note that DAGCombine should re-form any pre-increment load(s) from
11547 // what is produced here if that makes sense.
11548 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
11551 DCI.CombineTo(Bitcast2, FloatLoad);
11552 DCI.CombineTo(Bitcast, FloatLoad2);
11554 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
11555 SDValue(FloatLoad2.getNode(), 1));
11559 if (ReplaceTwoFloatLoad())
11560 return SDValue(N, 0);
11562 EVT MemVT = LD->getMemoryVT();
11563 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
11564 unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
11565 Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
11566 unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
11567 if (LD->isUnindexed() && VT.isVector() &&
11568 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
11569 // P8 and later hardware should just use LOAD.
11570 !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
11571 VT == MVT::v4i32 || VT == MVT::v4f32)) ||
11572 (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
11573 LD->getAlignment() >= ScalarABIAlignment)) &&
11574 LD->getAlignment() < ABIAlignment) {
11575 // This is a type-legal unaligned Altivec or QPX load.
11576 SDValue Chain = LD->getChain();
11577 SDValue Ptr = LD->getBasePtr();
11578 bool isLittleEndian = Subtarget.isLittleEndian();
11580 // This implements the loading of unaligned vectors as described in
11581 // the venerable Apple Velocity Engine overview. Specifically:
11582 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
11583 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
11585 // The general idea is to expand a sequence of one or more unaligned
11586 // loads into an alignment-based permutation-control instruction (lvsl
11587 // or lvsr), a series of regular vector loads (which always truncate
11588 // their input address to an aligned address), and a series of
11589 // permutations. The results of these permutations are the requested
11590 // loaded values. The trick is that the last "extra" load is not taken
11591 // from the address you might suspect (sizeof(vector) bytes after the
11592 // last requested load), but rather sizeof(vector) - 1 bytes after the
11593 // last requested vector. The point of this is to avoid a page fault if
11594 // the base address happened to be aligned. This works because if the
11595 // base address is aligned, then adding less than a full vector length
11596 // will cause the last vector in the sequence to be (re)loaded.
11597 // Otherwise, the next vector will be fetched as you might suspect was
11600 // We might be able to reuse the permutation generation from
11601 // a different base address offset from this one by an aligned amount.
11602 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
11603 // optimization later.
11604 Intrinsic::ID Intr, IntrLD, IntrPerm;
11605 MVT PermCntlTy, PermTy, LDTy;
11606 if (Subtarget.hasAltivec()) {
11607 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr :
11608 Intrinsic::ppc_altivec_lvsl;
11609 IntrLD = Intrinsic::ppc_altivec_lvx;
11610 IntrPerm = Intrinsic::ppc_altivec_vperm;
11611 PermCntlTy = MVT::v16i8;
11612 PermTy = MVT::v4i32;
11615 Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
11616 Intrinsic::ppc_qpx_qvlpcls;
11617 IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
11618 Intrinsic::ppc_qpx_qvlfs;
11619 IntrPerm = Intrinsic::ppc_qpx_qvfperm;
11620 PermCntlTy = MVT::v4f64;
11621 PermTy = MVT::v4f64;
11622 LDTy = MemVT.getSimpleVT();
11625 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
11627 // Create the new MMO for the new base load. It is like the original MMO,
11628 // but represents an area in memory almost twice the vector size centered
11629 // on the original address. If the address is unaligned, we might start
11630 // reading up to (sizeof(vector)-1) bytes below the address of the
11631 // original unaligned load.
11632 MachineFunction &MF = DAG.getMachineFunction();
11633 MachineMemOperand *BaseMMO =
11634 MF.getMachineMemOperand(LD->getMemOperand(),
11635 -(long)MemVT.getStoreSize()+1,
11636 2*MemVT.getStoreSize()-1);
11638 // Create the new base load.
11640 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
11641 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
11643 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
11644 DAG.getVTList(PermTy, MVT::Other),
11645 BaseLoadOps, LDTy, BaseMMO);
11647 // Note that the value of IncOffset (which is provided to the next
11648 // load's pointer info offset value, and thus used to calculate the
11649 // alignment), and the value of IncValue (which is actually used to
11650 // increment the pointer value) are different! This is because we
11651 // require the next load to appear to be aligned, even though it
11652 // is actually offset from the base pointer by a lesser amount.
11653 int IncOffset = VT.getSizeInBits() / 8;
11654 int IncValue = IncOffset;
11656 // Walk (both up and down) the chain looking for another load at the real
11657 // (aligned) offset (the alignment of the other load does not matter in
11658 // this case). If found, then do not use the offset reduction trick, as
11659 // that will prevent the loads from being later combined (as they would
11660 // otherwise be duplicates).
11661 if (!findConsecutiveLoad(LD, DAG))
11664 SDValue Increment =
11665 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
11666 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
11668 MachineMemOperand *ExtraMMO =
11669 MF.getMachineMemOperand(LD->getMemOperand(),
11670 1, 2*MemVT.getStoreSize()-1);
11671 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
11672 SDValue ExtraLoad =
11673 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
11674 DAG.getVTList(PermTy, MVT::Other),
11675 ExtraLoadOps, LDTy, ExtraMMO);
11677 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
11678 BaseLoad.getValue(1), ExtraLoad.getValue(1));
11680 // Because vperm has a big-endian bias, we must reverse the order
11681 // of the input vectors and complement the permute control vector
11682 // when generating little endian code. We have already handled the
11683 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
11684 // and ExtraLoad here.
11686 if (isLittleEndian)
11687 Perm = BuildIntrinsicOp(IntrPerm,
11688 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
11690 Perm = BuildIntrinsicOp(IntrPerm,
11691 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
11694 Perm = Subtarget.hasAltivec() ?
11695 DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
11696 DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
11697 DAG.getTargetConstant(1, dl, MVT::i64));
11698 // second argument is 1 because this rounding
11699 // is always exact.
11701 // The output of the permutation is our loaded result, the TokenFactor is
11703 DCI.CombineTo(N, Perm, TF);
11704 return SDValue(N, 0);
11708 case ISD::INTRINSIC_WO_CHAIN: {
11709 bool isLittleEndian = Subtarget.isLittleEndian();
11710 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11711 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
11712 : Intrinsic::ppc_altivec_lvsl);
11713 if ((IID == Intr ||
11714 IID == Intrinsic::ppc_qpx_qvlpcld ||
11715 IID == Intrinsic::ppc_qpx_qvlpcls) &&
11716 N->getOperand(1)->getOpcode() == ISD::ADD) {
11717 SDValue Add = N->getOperand(1);
11719 int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
11720 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
11722 if (DAG.MaskedValueIsZero(Add->getOperand(1),
11723 APInt::getAllOnesValue(Bits /* alignment */)
11724 .zext(Add.getScalarValueSizeInBits()))) {
11725 SDNode *BasePtr = Add->getOperand(0).getNode();
11726 for (SDNode::use_iterator UI = BasePtr->use_begin(),
11727 UE = BasePtr->use_end();
11729 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11730 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
11731 // We've found another LVSL/LVSR, and this address is an aligned
11732 // multiple of that one. The results will be the same, so use the
11733 // one we've just found instead.
11735 return SDValue(*UI, 0);
11740 if (isa<ConstantSDNode>(Add->getOperand(1))) {
11741 SDNode *BasePtr = Add->getOperand(0).getNode();
11742 for (SDNode::use_iterator UI = BasePtr->use_begin(),
11743 UE = BasePtr->use_end(); UI != UE; ++UI) {
11744 if (UI->getOpcode() == ISD::ADD &&
11745 isa<ConstantSDNode>(UI->getOperand(1)) &&
11746 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
11747 cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
11748 (1ULL << Bits) == 0) {
11749 SDNode *OtherAdd = *UI;
11750 for (SDNode::use_iterator VI = OtherAdd->use_begin(),
11751 VE = OtherAdd->use_end(); VI != VE; ++VI) {
11752 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11753 cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
11754 return SDValue(*VI, 0);
11764 case ISD::INTRINSIC_W_CHAIN:
11765 // For little endian, VSX loads require generating lxvd2x/xxswapd.
11766 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
11767 if (Subtarget.needsSwapsForVSXMemOps()) {
11768 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11771 case Intrinsic::ppc_vsx_lxvw4x:
11772 case Intrinsic::ppc_vsx_lxvd2x:
11773 return expandVSXLoadForLE(N, DCI);
11777 case ISD::INTRINSIC_VOID:
11778 // For little endian, VSX stores require generating xxswapd/stxvd2x.
11779 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
11780 if (Subtarget.needsSwapsForVSXMemOps()) {
11781 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11784 case Intrinsic::ppc_vsx_stxvw4x:
11785 case Intrinsic::ppc_vsx_stxvd2x:
11786 return expandVSXStoreForLE(N, DCI);
11791 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
11792 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
11793 N->getOperand(0).hasOneUse() &&
11794 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
11795 (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11796 N->getValueType(0) == MVT::i64))) {
11797 SDValue Load = N->getOperand(0);
11798 LoadSDNode *LD = cast<LoadSDNode>(Load);
11799 // Create the byte-swapping load.
11801 LD->getChain(), // Chain
11802 LD->getBasePtr(), // Ptr
11803 DAG.getValueType(N->getValueType(0)) // VT
11806 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
11807 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
11808 MVT::i64 : MVT::i32, MVT::Other),
11809 Ops, LD->getMemoryVT(), LD->getMemOperand());
11811 // If this is an i16 load, insert the truncate.
11812 SDValue ResVal = BSLoad;
11813 if (N->getValueType(0) == MVT::i16)
11814 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
11816 // First, combine the bswap away. This makes the value produced by the
11818 DCI.CombineTo(N, ResVal);
11820 // Next, combine the load away, we give it a bogus result value but a real
11821 // chain result. The result value is dead because the bswap is dead.
11822 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
11824 // Return N so it doesn't get rechecked!
11825 return SDValue(N, 0);
11829 // If a VCMPo node already exists with exactly the same operands as this
11830 // node, use its result instead of this node (VCMPo computes both a CR6 and
11831 // a normal output).
11833 if (!N->getOperand(0).hasOneUse() &&
11834 !N->getOperand(1).hasOneUse() &&
11835 !N->getOperand(2).hasOneUse()) {
11837 // Scan all of the users of the LHS, looking for VCMPo's that match.
11838 SDNode *VCMPoNode = nullptr;
11840 SDNode *LHSN = N->getOperand(0).getNode();
11841 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
11843 if (UI->getOpcode() == PPCISD::VCMPo &&
11844 UI->getOperand(1) == N->getOperand(1) &&
11845 UI->getOperand(2) == N->getOperand(2) &&
11846 UI->getOperand(0) == N->getOperand(0)) {
11851 // If there is no VCMPo node, or if the flag value has a single use, don't
11853 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
11856 // Look at the (necessarily single) use of the flag value. If it has a
11857 // chain, this transformation is more complex. Note that multiple things
11858 // could use the value result, which we should ignore.
11859 SDNode *FlagUser = nullptr;
11860 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
11861 FlagUser == nullptr; ++UI) {
11862 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
11863 SDNode *User = *UI;
11864 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
11865 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
11872 // If the user is a MFOCRF instruction, we know this is safe.
11873 // Otherwise we give up for right now.
11874 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
11875 return SDValue(VCMPoNode, 0);
11878 case ISD::BRCOND: {
11879 SDValue Cond = N->getOperand(1);
11880 SDValue Target = N->getOperand(2);
11882 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11883 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
11884 Intrinsic::ppc_is_decremented_ctr_nonzero) {
11886 // We now need to make the intrinsic dead (it cannot be instruction
11888 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
11889 assert(Cond.getNode()->hasOneUse() &&
11890 "Counter decrement has more than one use");
11892 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
11893 N->getOperand(0), Target);
11898 // If this is a branch on an altivec predicate comparison, lower this so
11899 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
11900 // lowering is done pre-legalize, because the legalizer lowers the predicate
11901 // compare down to code that is difficult to reassemble.
11902 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
11903 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
11905 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
11906 // value. If so, pass-through the AND to get to the intrinsic.
11907 if (LHS.getOpcode() == ISD::AND &&
11908 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11909 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
11910 Intrinsic::ppc_is_decremented_ctr_nonzero &&
11911 isa<ConstantSDNode>(LHS.getOperand(1)) &&
11912 !isNullConstant(LHS.getOperand(1)))
11913 LHS = LHS.getOperand(0);
11915 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11916 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
11917 Intrinsic::ppc_is_decremented_ctr_nonzero &&
11918 isa<ConstantSDNode>(RHS)) {
11919 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11920 "Counter decrement comparison is not EQ or NE");
11922 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11923 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
11924 (CC == ISD::SETNE && !Val);
11926 // We now need to make the intrinsic dead (it cannot be instruction
11928 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
11929 assert(LHS.getNode()->hasOneUse() &&
11930 "Counter decrement has more than one use");
11932 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
11933 N->getOperand(0), N->getOperand(4));
11939 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11940 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
11941 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
11942 assert(isDot && "Can't compare against a vector result!");
11944 // If this is a comparison against something other than 0/1, then we know
11945 // that the condition is never/always true.
11946 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11947 if (Val != 0 && Val != 1) {
11948 if (CC == ISD::SETEQ) // Cond never true, remove branch.
11949 return N->getOperand(0);
11950 // Always !=, turn it into an unconditional branch.
11951 return DAG.getNode(ISD::BR, dl, MVT::Other,
11952 N->getOperand(0), N->getOperand(4));
11955 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
11957 // Create the PPCISD altivec 'dot' comparison node.
11959 LHS.getOperand(2), // LHS of compare
11960 LHS.getOperand(3), // RHS of compare
11961 DAG.getConstant(CompareOpc, dl, MVT::i32)
11963 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
11964 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
11966 // Unpack the result based on how the target uses it.
11967 PPC::Predicate CompOpc;
11968 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
11969 default: // Can't happen, don't crash on invalid number though.
11970 case 0: // Branch on the value of the EQ bit of CR6.
11971 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
11973 case 1: // Branch on the inverted value of the EQ bit of CR6.
11974 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
11976 case 2: // Branch on the value of the LT bit of CR6.
11977 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
11979 case 3: // Branch on the inverted value of the LT bit of CR6.
11980 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
11984 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
11985 DAG.getConstant(CompOpc, dl, MVT::i32),
11986 DAG.getRegister(PPC::CR6, MVT::i32),
11987 N->getOperand(4), CompNode.getValue(1));
11991 case ISD::BUILD_VECTOR:
11992 return DAGCombineBuildVector(N, DCI);
11999 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
12001 std::vector<SDNode *> *Created) const {
12002 // fold (sdiv X, pow2)
12003 EVT VT = N->getValueType(0);
12004 if (VT == MVT::i64 && !Subtarget.isPPC64())
12006 if ((VT != MVT::i32 && VT != MVT::i64) ||
12007 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
12011 SDValue N0 = N->getOperand(0);
12013 bool IsNegPow2 = (-Divisor).isPowerOf2();
12014 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
12015 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
12017 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
12019 Created->push_back(Op.getNode());
12022 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
12024 Created->push_back(Op.getNode());
12030 //===----------------------------------------------------------------------===//
12031 // Inline Assembly Support
12032 //===----------------------------------------------------------------------===//
12034 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12036 const APInt &DemandedElts,
12037 const SelectionDAG &DAG,
12038 unsigned Depth) const {
12040 switch (Op.getOpcode()) {
12042 case PPCISD::LBRX: {
12043 // lhbrx is known to have the top bits cleared out.
12044 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
12045 Known.Zero = 0xFFFF0000;
12048 case ISD::INTRINSIC_WO_CHAIN: {
12049 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
12051 case Intrinsic::ppc_altivec_vcmpbfp_p:
12052 case Intrinsic::ppc_altivec_vcmpeqfp_p:
12053 case Intrinsic::ppc_altivec_vcmpequb_p:
12054 case Intrinsic::ppc_altivec_vcmpequh_p:
12055 case Intrinsic::ppc_altivec_vcmpequw_p:
12056 case Intrinsic::ppc_altivec_vcmpequd_p:
12057 case Intrinsic::ppc_altivec_vcmpgefp_p:
12058 case Intrinsic::ppc_altivec_vcmpgtfp_p:
12059 case Intrinsic::ppc_altivec_vcmpgtsb_p:
12060 case Intrinsic::ppc_altivec_vcmpgtsh_p:
12061 case Intrinsic::ppc_altivec_vcmpgtsw_p:
12062 case Intrinsic::ppc_altivec_vcmpgtsd_p:
12063 case Intrinsic::ppc_altivec_vcmpgtub_p:
12064 case Intrinsic::ppc_altivec_vcmpgtuh_p:
12065 case Intrinsic::ppc_altivec_vcmpgtuw_p:
12066 case Intrinsic::ppc_altivec_vcmpgtud_p:
12067 Known.Zero = ~1U; // All bits but the low one are known to be zero.
12074 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12075 switch (Subtarget.getDarwinDirective()) {
12078 case PPC::DIR_PWR4:
12079 case PPC::DIR_PWR5:
12080 case PPC::DIR_PWR5X:
12081 case PPC::DIR_PWR6:
12082 case PPC::DIR_PWR6X:
12083 case PPC::DIR_PWR7:
12084 case PPC::DIR_PWR8:
12085 case PPC::DIR_PWR9: {
12089 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
12091 // For small loops (between 5 and 8 instructions), align to a 32-byte
12092 // boundary so that the entire loop fits in one instruction-cache line.
12093 uint64_t LoopSize = 0;
12094 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
12095 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
12096 LoopSize += TII->getInstSizeInBytes(*J);
12101 if (LoopSize > 16 && LoopSize <= 32)
12108 return TargetLowering::getPrefLoopAlignment(ML);
12111 /// getConstraintType - Given a constraint, return the type of
12112 /// constraint it is for this target.
12113 PPCTargetLowering::ConstraintType
12114 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
12115 if (Constraint.size() == 1) {
12116 switch (Constraint[0]) {
12124 return C_RegisterClass;
12126 // FIXME: While Z does indicate a memory constraint, it specifically
12127 // indicates an r+r address (used in conjunction with the 'y' modifier
12128 // in the replacement string). Currently, we're forcing the base
12129 // register to be r0 in the asm printer (which is interpreted as zero)
12130 // and forming the complete address in the second register. This is
12134 } else if (Constraint == "wc") { // individual CR bits.
12135 return C_RegisterClass;
12136 } else if (Constraint == "wa" || Constraint == "wd" ||
12137 Constraint == "wf" || Constraint == "ws") {
12138 return C_RegisterClass; // VSX registers.
12140 return TargetLowering::getConstraintType(Constraint);
12143 /// Examine constraint type and operand type and determine a weight value.
12144 /// This object must already have been set up with the operand type
12145 /// and the current alternative constraint selected.
12146 TargetLowering::ConstraintWeight
12147 PPCTargetLowering::getSingleConstraintMatchWeight(
12148 AsmOperandInfo &info, const char *constraint) const {
12149 ConstraintWeight weight = CW_Invalid;
12150 Value *CallOperandVal = info.CallOperandVal;
12151 // If we don't have a value, we can't do a match,
12152 // but allow it at the lowest weight.
12153 if (!CallOperandVal)
12155 Type *type = CallOperandVal->getType();
12157 // Look at the constraint type.
12158 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
12159 return CW_Register; // an individual CR bit.
12160 else if ((StringRef(constraint) == "wa" ||
12161 StringRef(constraint) == "wd" ||
12162 StringRef(constraint) == "wf") &&
12163 type->isVectorTy())
12164 return CW_Register;
12165 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
12166 return CW_Register;
12168 switch (*constraint) {
12170 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12173 if (type->isIntegerTy())
12174 weight = CW_Register;
12177 if (type->isFloatTy())
12178 weight = CW_Register;
12181 if (type->isDoubleTy())
12182 weight = CW_Register;
12185 if (type->isVectorTy())
12186 weight = CW_Register;
12189 weight = CW_Register;
12192 weight = CW_Memory;
12198 std::pair<unsigned, const TargetRegisterClass *>
12199 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
12200 StringRef Constraint,
12202 if (Constraint.size() == 1) {
12203 // GCC RS6000 Constraint Letters
12204 switch (Constraint[0]) {
12205 case 'b': // R1-R31
12206 if (VT == MVT::i64 && Subtarget.isPPC64())
12207 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
12208 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
12209 case 'r': // R0-R31
12210 if (VT == MVT::i64 && Subtarget.isPPC64())
12211 return std::make_pair(0U, &PPC::G8RCRegClass);
12212 return std::make_pair(0U, &PPC::GPRCRegClass);
12213 // 'd' and 'f' constraints are both defined to be "the floating point
12214 // registers", where one is for 32-bit and the other for 64-bit. We don't
12215 // really care overly much here so just give them all the same reg classes.
12218 if (VT == MVT::f32 || VT == MVT::i32)
12219 return std::make_pair(0U, &PPC::F4RCRegClass);
12220 if (VT == MVT::f64 || VT == MVT::i64)
12221 return std::make_pair(0U, &PPC::F8RCRegClass);
12222 if (VT == MVT::v4f64 && Subtarget.hasQPX())
12223 return std::make_pair(0U, &PPC::QFRCRegClass);
12224 if (VT == MVT::v4f32 && Subtarget.hasQPX())
12225 return std::make_pair(0U, &PPC::QSRCRegClass);
12228 if (VT == MVT::v4f64 && Subtarget.hasQPX())
12229 return std::make_pair(0U, &PPC::QFRCRegClass);
12230 if (VT == MVT::v4f32 && Subtarget.hasQPX())
12231 return std::make_pair(0U, &PPC::QSRCRegClass);
12232 if (Subtarget.hasAltivec())
12233 return std::make_pair(0U, &PPC::VRRCRegClass);
12235 return std::make_pair(0U, &PPC::CRRCRegClass);
12237 } else if (Constraint == "wc" && Subtarget.useCRBits()) {
12238 // An individual CR bit.
12239 return std::make_pair(0U, &PPC::CRBITRCRegClass);
12240 } else if ((Constraint == "wa" || Constraint == "wd" ||
12241 Constraint == "wf") && Subtarget.hasVSX()) {
12242 return std::make_pair(0U, &PPC::VSRCRegClass);
12243 } else if (Constraint == "ws" && Subtarget.hasVSX()) {
12244 if (VT == MVT::f32 && Subtarget.hasP8Vector())
12245 return std::make_pair(0U, &PPC::VSSRCRegClass);
12247 return std::make_pair(0U, &PPC::VSFRCRegClass);
12250 std::pair<unsigned, const TargetRegisterClass *> R =
12251 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12253 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
12254 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
12255 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
12257 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
12258 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
12259 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
12260 PPC::GPRCRegClass.contains(R.first))
12261 return std::make_pair(TRI->getMatchingSuperReg(R.first,
12262 PPC::sub_32, &PPC::G8RCRegClass),
12263 &PPC::G8RCRegClass);
12265 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
12266 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
12267 R.first = PPC::CR0;
12268 R.second = &PPC::CRRCRegClass;
12274 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12275 /// vector. If it is invalid, don't add anything to Ops.
12276 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12277 std::string &Constraint,
12278 std::vector<SDValue>&Ops,
12279 SelectionDAG &DAG) const {
12282 // Only support length 1 constraints.
12283 if (Constraint.length() > 1) return;
12285 char Letter = Constraint[0];
12296 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
12297 if (!CST) return; // Must be an immediate to match.
12299 int64_t Value = CST->getSExtValue();
12300 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
12301 // numbers are printed as such.
12303 default: llvm_unreachable("Unknown constraint letter!");
12304 case 'I': // "I" is a signed 16-bit constant.
12305 if (isInt<16>(Value))
12306 Result = DAG.getTargetConstant(Value, dl, TCVT);
12308 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
12309 if (isShiftedUInt<16, 16>(Value))
12310 Result = DAG.getTargetConstant(Value, dl, TCVT);
12312 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
12313 if (isShiftedInt<16, 16>(Value))
12314 Result = DAG.getTargetConstant(Value, dl, TCVT);
12316 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
12317 if (isUInt<16>(Value))
12318 Result = DAG.getTargetConstant(Value, dl, TCVT);
12320 case 'M': // "M" is a constant that is greater than 31.
12322 Result = DAG.getTargetConstant(Value, dl, TCVT);
12324 case 'N': // "N" is a positive constant that is an exact power of two.
12325 if (Value > 0 && isPowerOf2_64(Value))
12326 Result = DAG.getTargetConstant(Value, dl, TCVT);
12328 case 'O': // "O" is the constant zero.
12330 Result = DAG.getTargetConstant(Value, dl, TCVT);
12332 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
12333 if (isInt<16>(-Value))
12334 Result = DAG.getTargetConstant(Value, dl, TCVT);
12341 if (Result.getNode()) {
12342 Ops.push_back(Result);
12346 // Handle standard constraint letters.
12347 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12350 // isLegalAddressingMode - Return true if the addressing mode represented
12351 // by AM is legal for this target, for a load/store of the specified type.
12352 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12353 const AddrMode &AM, Type *Ty,
12354 unsigned AS) const {
12355 // PPC does not allow r+i addressing modes for vectors!
12356 if (Ty->isVectorTy() && AM.BaseOffs != 0)
12359 // PPC allows a sign-extended 16-bit immediate field.
12360 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
12363 // No global is ever allowed as a base.
12367 // PPC only support r+r,
12368 switch (AM.Scale) {
12369 case 0: // "r+i" or just "i", depending on HasBaseReg.
12372 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
12374 // Otherwise we have r+r or r+i.
12377 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
12379 // Allow 2*r as r+r.
12382 // No other scales are supported.
12389 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
12390 SelectionDAG &DAG) const {
12391 MachineFunction &MF = DAG.getMachineFunction();
12392 MachineFrameInfo &MFI = MF.getFrameInfo();
12393 MFI.setReturnAddressIsTaken(true);
12395 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12399 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12401 // Make sure the function does not optimize away the store of the RA to
12403 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
12404 FuncInfo->setLRStoreRequired();
12405 bool isPPC64 = Subtarget.isPPC64();
12406 auto PtrVT = getPointerTy(MF.getDataLayout());
12409 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12411 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
12412 isPPC64 ? MVT::i64 : MVT::i32);
12413 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12414 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
12415 MachinePointerInfo());
12418 // Just load the return address off the stack.
12419 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
12420 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
12421 MachinePointerInfo());
12424 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
12425 SelectionDAG &DAG) const {
12427 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12429 MachineFunction &MF = DAG.getMachineFunction();
12430 MachineFrameInfo &MFI = MF.getFrameInfo();
12431 MFI.setFrameAddressIsTaken(true);
12433 EVT PtrVT = getPointerTy(MF.getDataLayout());
12434 bool isPPC64 = PtrVT == MVT::i64;
12436 // Naked functions never have a frame pointer, and so we use r1. For all
12437 // other functions, this decision must be delayed until during PEI.
12439 if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
12440 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
12442 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
12444 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
12447 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
12448 FrameAddr, MachinePointerInfo());
12452 // FIXME? Maybe this could be a TableGen attribute on some registers and
12453 // this table could be generated automatically from RegInfo.
12454 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
12455 SelectionDAG &DAG) const {
12456 bool isPPC64 = Subtarget.isPPC64();
12457 bool isDarwinABI = Subtarget.isDarwinABI();
12459 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
12460 (!isPPC64 && VT != MVT::i32))
12461 report_fatal_error("Invalid register global variable type");
12463 bool is64Bit = isPPC64 && VT == MVT::i64;
12464 unsigned Reg = StringSwitch<unsigned>(RegName)
12465 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
12466 .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
12467 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
12468 (is64Bit ? PPC::X13 : PPC::R13))
12473 report_fatal_error("Invalid register name global variable");
12477 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
12478 // The PowerPC target isn't yet aware of offsets.
12482 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
12484 unsigned Intrinsic) const {
12485 switch (Intrinsic) {
12486 case Intrinsic::ppc_qpx_qvlfd:
12487 case Intrinsic::ppc_qpx_qvlfs:
12488 case Intrinsic::ppc_qpx_qvlfcd:
12489 case Intrinsic::ppc_qpx_qvlfcs:
12490 case Intrinsic::ppc_qpx_qvlfiwa:
12491 case Intrinsic::ppc_qpx_qvlfiwz:
12492 case Intrinsic::ppc_altivec_lvx:
12493 case Intrinsic::ppc_altivec_lvxl:
12494 case Intrinsic::ppc_altivec_lvebx:
12495 case Intrinsic::ppc_altivec_lvehx:
12496 case Intrinsic::ppc_altivec_lvewx:
12497 case Intrinsic::ppc_vsx_lxvd2x:
12498 case Intrinsic::ppc_vsx_lxvw4x: {
12500 switch (Intrinsic) {
12501 case Intrinsic::ppc_altivec_lvebx:
12504 case Intrinsic::ppc_altivec_lvehx:
12507 case Intrinsic::ppc_altivec_lvewx:
12510 case Intrinsic::ppc_vsx_lxvd2x:
12513 case Intrinsic::ppc_qpx_qvlfd:
12516 case Intrinsic::ppc_qpx_qvlfs:
12519 case Intrinsic::ppc_qpx_qvlfcd:
12522 case Intrinsic::ppc_qpx_qvlfcs:
12530 Info.opc = ISD::INTRINSIC_W_CHAIN;
12532 Info.ptrVal = I.getArgOperand(0);
12533 Info.offset = -VT.getStoreSize()+1;
12534 Info.size = 2*VT.getStoreSize()-1;
12537 Info.readMem = true;
12538 Info.writeMem = false;
12541 case Intrinsic::ppc_qpx_qvlfda:
12542 case Intrinsic::ppc_qpx_qvlfsa:
12543 case Intrinsic::ppc_qpx_qvlfcda:
12544 case Intrinsic::ppc_qpx_qvlfcsa:
12545 case Intrinsic::ppc_qpx_qvlfiwaa:
12546 case Intrinsic::ppc_qpx_qvlfiwza: {
12548 switch (Intrinsic) {
12549 case Intrinsic::ppc_qpx_qvlfda:
12552 case Intrinsic::ppc_qpx_qvlfsa:
12555 case Intrinsic::ppc_qpx_qvlfcda:
12558 case Intrinsic::ppc_qpx_qvlfcsa:
12566 Info.opc = ISD::INTRINSIC_W_CHAIN;
12568 Info.ptrVal = I.getArgOperand(0);
12570 Info.size = VT.getStoreSize();
12573 Info.readMem = true;
12574 Info.writeMem = false;
12577 case Intrinsic::ppc_qpx_qvstfd:
12578 case Intrinsic::ppc_qpx_qvstfs:
12579 case Intrinsic::ppc_qpx_qvstfcd:
12580 case Intrinsic::ppc_qpx_qvstfcs:
12581 case Intrinsic::ppc_qpx_qvstfiw:
12582 case Intrinsic::ppc_altivec_stvx:
12583 case Intrinsic::ppc_altivec_stvxl:
12584 case Intrinsic::ppc_altivec_stvebx:
12585 case Intrinsic::ppc_altivec_stvehx:
12586 case Intrinsic::ppc_altivec_stvewx:
12587 case Intrinsic::ppc_vsx_stxvd2x:
12588 case Intrinsic::ppc_vsx_stxvw4x: {
12590 switch (Intrinsic) {
12591 case Intrinsic::ppc_altivec_stvebx:
12594 case Intrinsic::ppc_altivec_stvehx:
12597 case Intrinsic::ppc_altivec_stvewx:
12600 case Intrinsic::ppc_vsx_stxvd2x:
12603 case Intrinsic::ppc_qpx_qvstfd:
12606 case Intrinsic::ppc_qpx_qvstfs:
12609 case Intrinsic::ppc_qpx_qvstfcd:
12612 case Intrinsic::ppc_qpx_qvstfcs:
12620 Info.opc = ISD::INTRINSIC_VOID;
12622 Info.ptrVal = I.getArgOperand(1);
12623 Info.offset = -VT.getStoreSize()+1;
12624 Info.size = 2*VT.getStoreSize()-1;
12627 Info.readMem = false;
12628 Info.writeMem = true;
12631 case Intrinsic::ppc_qpx_qvstfda:
12632 case Intrinsic::ppc_qpx_qvstfsa:
12633 case Intrinsic::ppc_qpx_qvstfcda:
12634 case Intrinsic::ppc_qpx_qvstfcsa:
12635 case Intrinsic::ppc_qpx_qvstfiwa: {
12637 switch (Intrinsic) {
12638 case Intrinsic::ppc_qpx_qvstfda:
12641 case Intrinsic::ppc_qpx_qvstfsa:
12644 case Intrinsic::ppc_qpx_qvstfcda:
12647 case Intrinsic::ppc_qpx_qvstfcsa:
12655 Info.opc = ISD::INTRINSIC_VOID;
12657 Info.ptrVal = I.getArgOperand(1);
12659 Info.size = VT.getStoreSize();
12662 Info.readMem = false;
12663 Info.writeMem = true;
12673 /// getOptimalMemOpType - Returns the target specific optimal type for load
12674 /// and store operations as a result of memset, memcpy, and memmove
12675 /// lowering. If DstAlign is zero that means it's safe to destination
12676 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
12677 /// means there isn't a need to check it against alignment requirement,
12678 /// probably because the source does not need to be loaded. If 'IsMemset' is
12679 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
12680 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
12681 /// source is constant so it does not need to be loaded.
12682 /// It returns EVT::Other if the type should be determined using generic
12683 /// target-independent logic.
12684 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
12685 unsigned DstAlign, unsigned SrcAlign,
12686 bool IsMemset, bool ZeroMemset,
12688 MachineFunction &MF) const {
12689 if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
12690 const Function *F = MF.getFunction();
12691 // When expanding a memset, require at least two QPX instructions to cover
12692 // the cost of loading the value to be stored from the constant pool.
12693 if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
12694 (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
12695 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
12699 // We should use Altivec/VSX loads and stores when available. For unaligned
12700 // addresses, unaligned VSX loads are only fast starting with the P8.
12701 if (Subtarget.hasAltivec() && Size >= 16 &&
12702 (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
12703 ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
12707 if (Subtarget.isPPC64()) {
12714 /// \brief Returns true if it is beneficial to convert a load of a constant
12715 /// to just the constant itself.
12716 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
12718 assert(Ty->isIntegerTy());
12720 unsigned BitSize = Ty->getPrimitiveSizeInBits();
12721 return !(BitSize == 0 || BitSize > 64);
12724 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12725 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12727 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12728 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12729 return NumBits1 == 64 && NumBits2 == 32;
12732 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12733 if (!VT1.isInteger() || !VT2.isInteger())
12735 unsigned NumBits1 = VT1.getSizeInBits();
12736 unsigned NumBits2 = VT2.getSizeInBits();
12737 return NumBits1 == 64 && NumBits2 == 32;
12740 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12741 // Generally speaking, zexts are not free, but they are free when they can be
12742 // folded with other operations.
12743 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
12744 EVT MemVT = LD->getMemoryVT();
12745 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
12746 (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
12747 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
12748 LD->getExtensionType() == ISD::ZEXTLOAD))
12752 // FIXME: Add other cases...
12753 // - 32-bit shifts with a zext to i64
12754 // - zext after ctlz, bswap, etc.
12755 // - zext after and by a constant mask
12757 return TargetLowering::isZExtFree(Val, VT2);
12760 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
12761 assert(VT.isFloatingPoint());
12765 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12766 return isInt<16>(Imm) || isUInt<16>(Imm);
12769 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12770 return isInt<16>(Imm) || isUInt<16>(Imm);
12773 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12776 bool *Fast) const {
12777 if (DisablePPCUnaligned)
12780 // PowerPC supports unaligned memory access for simple non-vector types.
12781 // Although accessing unaligned addresses is not as efficient as accessing
12782 // aligned addresses, it is generally more efficient than manual expansion,
12783 // and generally only traps for software emulation when crossing page
12786 if (!VT.isSimple())
12789 if (VT.getSimpleVT().isVector()) {
12790 if (Subtarget.hasVSX()) {
12791 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
12792 VT != MVT::v4f32 && VT != MVT::v4i32)
12799 if (VT == MVT::ppcf128)
12808 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
12809 VT = VT.getScalarType();
12811 if (!VT.isSimple())
12814 switch (VT.getSimpleVT().SimpleTy) {
12826 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
12827 // LR is a callee-save register, but we must treat it as clobbered by any call
12828 // site. Hence we include LR in the scratch registers, which are in turn added
12829 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
12830 // to CTR, which is used by any indirect call.
12831 static const MCPhysReg ScratchRegs[] = {
12832 PPC::X12, PPC::LR8, PPC::CTR8, 0
12835 return ScratchRegs;
12838 unsigned PPCTargetLowering::getExceptionPointerRegister(
12839 const Constant *PersonalityFn) const {
12840 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
12843 unsigned PPCTargetLowering::getExceptionSelectorRegister(
12844 const Constant *PersonalityFn) const {
12845 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
12849 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
12850 EVT VT , unsigned DefinedValues) const {
12851 if (VT == MVT::v2i64)
12852 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
12854 if (Subtarget.hasVSX() || Subtarget.hasQPX())
12857 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
12860 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
12861 if (DisableILPPref || Subtarget.enableMachineScheduler())
12862 return TargetLowering::getSchedulingPreference(N);
12867 // Create a fast isel object.
12869 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
12870 const TargetLibraryInfo *LibInfo) const {
12871 return PPC::createFastISel(FuncInfo, LibInfo);
12874 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12875 if (Subtarget.isDarwinABI()) return;
12876 if (!Subtarget.isPPC64()) return;
12878 // Update IsSplitCSR in PPCFunctionInfo
12879 PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
12880 PFI->setIsSplitCSR(true);
12883 void PPCTargetLowering::insertCopiesSplitCSR(
12884 MachineBasicBlock *Entry,
12885 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12886 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
12887 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12891 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12892 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12893 MachineBasicBlock::iterator MBBI = Entry->begin();
12894 for (const MCPhysReg *I = IStart; *I; ++I) {
12895 const TargetRegisterClass *RC = nullptr;
12896 if (PPC::G8RCRegClass.contains(*I))
12897 RC = &PPC::G8RCRegClass;
12898 else if (PPC::F8RCRegClass.contains(*I))
12899 RC = &PPC::F8RCRegClass;
12900 else if (PPC::CRRCRegClass.contains(*I))
12901 RC = &PPC::CRRCRegClass;
12902 else if (PPC::VRRCRegClass.contains(*I))
12903 RC = &PPC::VRRCRegClass;
12905 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12907 unsigned NewVR = MRI->createVirtualRegister(RC);
12908 // Create copy from CSR to a virtual register.
12909 // FIXME: this currently does not emit CFI pseudo-instructions, it works
12910 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12911 // nounwind. If we want to generalize this later, we may need to emit
12912 // CFI pseudo-instructions.
12913 assert(Entry->getParent()->getFunction()->hasFnAttribute(
12914 Attribute::NoUnwind) &&
12915 "Function should be nounwind in insertCopiesSplitCSR!");
12916 Entry->addLiveIn(*I);
12917 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12920 // Insert the copy-back instructions right before the terminator
12921 for (auto *Exit : Exits)
12922 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12923 TII->get(TargetOpcode::COPY), *I)
12928 // Override to enable LOAD_STACK_GUARD lowering on Linux.
12929 bool PPCTargetLowering::useLoadStackGuardNode() const {
12930 if (!Subtarget.isTargetLinux())
12931 return TargetLowering::useLoadStackGuardNode();
12935 // Override to disable global variable loading on Linux.
12936 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
12937 if (!Subtarget.isTargetLinux())
12938 return TargetLowering::insertSSPDeclarations(M);
12941 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
12942 if (!VT.isSimple() || !Subtarget.hasVSX())
12945 switch(VT.getSimpleVT().SimpleTy) {
12947 // For FP types that are currently not supported by PPC backend, return
12948 // false. Examples: f16, f80.
12953 return Imm.isPosZero();
12957 // For vector shift operation op, fold
12958 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
12959 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
12960 SelectionDAG &DAG) {
12961 SDValue N0 = N->getOperand(0);
12962 SDValue N1 = N->getOperand(1);
12963 EVT VT = N0.getValueType();
12964 unsigned OpSizeInBits = VT.getScalarSizeInBits();
12965 unsigned Opcode = N->getOpcode();
12966 unsigned TargetOpcode;
12970 llvm_unreachable("Unexpected shift operation");
12972 TargetOpcode = PPCISD::SHL;
12975 TargetOpcode = PPCISD::SRL;
12978 TargetOpcode = PPCISD::SRA;
12982 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
12983 N1->getOpcode() == ISD::AND)
12984 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
12985 if (Mask->getZExtValue() == OpSizeInBits - 1)
12986 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
12991 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
12992 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
12998 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
12999 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13005 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
13006 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))