1 //===-- AArch64ISelLowering.cpp - AArch64 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 defines the interfaces that AArch64 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "aarch64-isel"
17 #include "AArch64ISelLowering.h"
18 #include "AArch64MachineFunctionInfo.h"
19 #include "AArch64TargetMachine.h"
20 #include "AArch64TargetObjectFile.h"
21 #include "Utils/AArch64BaseInfo.h"
22 #include "llvm/CodeGen/Analysis.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
28 #include "llvm/IR/CallingConv.h"
32 static TargetLoweringObjectFile *createTLOF(AArch64TargetMachine &TM) {
33 const AArch64Subtarget *Subtarget = &TM.getSubtarget<AArch64Subtarget>();
35 if (Subtarget->isTargetLinux())
36 return new AArch64LinuxTargetObjectFile();
37 if (Subtarget->isTargetELF())
38 return new TargetLoweringObjectFileELF();
39 llvm_unreachable("unknown subtarget type");
42 AArch64TargetLowering::AArch64TargetLowering(AArch64TargetMachine &TM)
43 : TargetLowering(TM, createTLOF(TM)), Itins(TM.getInstrItineraryData()) {
45 const AArch64Subtarget *Subtarget = &TM.getSubtarget<AArch64Subtarget>();
47 // SIMD compares set the entire lane's bits to 1
48 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
50 // Scalar register <-> type mapping
51 addRegisterClass(MVT::i32, &AArch64::GPR32RegClass);
52 addRegisterClass(MVT::i64, &AArch64::GPR64RegClass);
53 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
54 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
55 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
56 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
58 if (Subtarget->hasNEON()) {
60 addRegisterClass(MVT::v1i8, &AArch64::FPR8RegClass);
61 addRegisterClass(MVT::v1i16, &AArch64::FPR16RegClass);
62 addRegisterClass(MVT::v1i32, &AArch64::FPR32RegClass);
63 addRegisterClass(MVT::v1i64, &AArch64::FPR64RegClass);
64 addRegisterClass(MVT::v1f32, &AArch64::FPR32RegClass);
65 addRegisterClass(MVT::v1f64, &AArch64::FPR64RegClass);
66 addRegisterClass(MVT::v8i8, &AArch64::FPR64RegClass);
67 addRegisterClass(MVT::v4i16, &AArch64::FPR64RegClass);
68 addRegisterClass(MVT::v2i32, &AArch64::FPR64RegClass);
69 addRegisterClass(MVT::v1i64, &AArch64::FPR64RegClass);
70 addRegisterClass(MVT::v2f32, &AArch64::FPR64RegClass);
71 addRegisterClass(MVT::v16i8, &AArch64::FPR128RegClass);
72 addRegisterClass(MVT::v8i16, &AArch64::FPR128RegClass);
73 addRegisterClass(MVT::v4i32, &AArch64::FPR128RegClass);
74 addRegisterClass(MVT::v2i64, &AArch64::FPR128RegClass);
75 addRegisterClass(MVT::v4f32, &AArch64::FPR128RegClass);
76 addRegisterClass(MVT::v2f64, &AArch64::FPR128RegClass);
79 computeRegisterProperties();
81 // We combine OR nodes for bitfield and NEON BSL operations.
82 setTargetDAGCombine(ISD::OR);
84 setTargetDAGCombine(ISD::AND);
85 setTargetDAGCombine(ISD::SRA);
86 setTargetDAGCombine(ISD::SRL);
87 setTargetDAGCombine(ISD::SHL);
89 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
91 // AArch64 does not have i1 loads, or much of anything for i1 really.
92 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
93 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
94 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
96 setStackPointerRegisterToSaveRestore(AArch64::XSP);
97 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
98 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
99 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
101 // We'll lower globals to wrappers for selection.
102 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
103 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
105 // A64 instructions have the comparison predicate attached to the user of the
106 // result, but having a separate comparison is valuable for matching.
107 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
108 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
109 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
110 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
112 setOperationAction(ISD::SELECT, MVT::i32, Custom);
113 setOperationAction(ISD::SELECT, MVT::i64, Custom);
114 setOperationAction(ISD::SELECT, MVT::f32, Custom);
115 setOperationAction(ISD::SELECT, MVT::f64, Custom);
117 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
118 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
119 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
120 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
122 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
124 setOperationAction(ISD::SETCC, MVT::i32, Custom);
125 setOperationAction(ISD::SETCC, MVT::i64, Custom);
126 setOperationAction(ISD::SETCC, MVT::f32, Custom);
127 setOperationAction(ISD::SETCC, MVT::f64, Custom);
129 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
130 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
131 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
133 setOperationAction(ISD::VASTART, MVT::Other, Custom);
134 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
135 setOperationAction(ISD::VAEND, MVT::Other, Expand);
136 setOperationAction(ISD::VAARG, MVT::Other, Expand);
138 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
140 setOperationAction(ISD::ROTL, MVT::i32, Expand);
141 setOperationAction(ISD::ROTL, MVT::i64, Expand);
143 setOperationAction(ISD::UREM, MVT::i32, Expand);
144 setOperationAction(ISD::UREM, MVT::i64, Expand);
145 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
146 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
148 setOperationAction(ISD::SREM, MVT::i32, Expand);
149 setOperationAction(ISD::SREM, MVT::i64, Expand);
150 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
151 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
153 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
154 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
156 // Legal floating-point operations.
157 setOperationAction(ISD::FABS, MVT::f32, Legal);
158 setOperationAction(ISD::FABS, MVT::f64, Legal);
160 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
161 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
163 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
164 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
166 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
167 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
169 setOperationAction(ISD::FNEG, MVT::f32, Legal);
170 setOperationAction(ISD::FNEG, MVT::f64, Legal);
172 setOperationAction(ISD::FRINT, MVT::f32, Legal);
173 setOperationAction(ISD::FRINT, MVT::f64, Legal);
175 setOperationAction(ISD::FSQRT, MVT::f32, Legal);
176 setOperationAction(ISD::FSQRT, MVT::f64, Legal);
178 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
179 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
181 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
182 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
183 setOperationAction(ISD::ConstantFP, MVT::f128, Legal);
185 // Illegal floating-point operations.
186 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
187 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
189 setOperationAction(ISD::FCOS, MVT::f32, Expand);
190 setOperationAction(ISD::FCOS, MVT::f64, Expand);
192 setOperationAction(ISD::FEXP, MVT::f32, Expand);
193 setOperationAction(ISD::FEXP, MVT::f64, Expand);
195 setOperationAction(ISD::FEXP2, MVT::f32, Expand);
196 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
198 setOperationAction(ISD::FLOG, MVT::f32, Expand);
199 setOperationAction(ISD::FLOG, MVT::f64, Expand);
201 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
202 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
204 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
205 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
207 setOperationAction(ISD::FPOW, MVT::f32, Expand);
208 setOperationAction(ISD::FPOW, MVT::f64, Expand);
210 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
211 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
213 setOperationAction(ISD::FREM, MVT::f32, Expand);
214 setOperationAction(ISD::FREM, MVT::f64, Expand);
216 setOperationAction(ISD::FSIN, MVT::f32, Expand);
217 setOperationAction(ISD::FSIN, MVT::f64, Expand);
219 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
220 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
222 // Virtually no operation on f128 is legal, but LLVM can't expand them when
223 // there's a valid register class, so we need custom operations in most cases.
224 setOperationAction(ISD::FABS, MVT::f128, Expand);
225 setOperationAction(ISD::FADD, MVT::f128, Custom);
226 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
227 setOperationAction(ISD::FCOS, MVT::f128, Expand);
228 setOperationAction(ISD::FDIV, MVT::f128, Custom);
229 setOperationAction(ISD::FMA, MVT::f128, Expand);
230 setOperationAction(ISD::FMUL, MVT::f128, Custom);
231 setOperationAction(ISD::FNEG, MVT::f128, Expand);
232 setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand);
233 setOperationAction(ISD::FP_ROUND, MVT::f128, Expand);
234 setOperationAction(ISD::FPOW, MVT::f128, Expand);
235 setOperationAction(ISD::FREM, MVT::f128, Expand);
236 setOperationAction(ISD::FRINT, MVT::f128, Expand);
237 setOperationAction(ISD::FSIN, MVT::f128, Expand);
238 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
239 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
240 setOperationAction(ISD::FSUB, MVT::f128, Custom);
241 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
242 setOperationAction(ISD::SETCC, MVT::f128, Custom);
243 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
244 setOperationAction(ISD::SELECT, MVT::f128, Expand);
245 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
246 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
248 // Lowering for many of the conversions is actually specified by the non-f128
249 // type. The LowerXXX function will be trivial when f128 isn't involved.
250 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
251 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
252 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
253 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
254 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
255 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
256 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
257 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
258 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
259 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
260 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
261 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
262 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
263 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
265 // This prevents LLVM trying to compress double constants into a floating
266 // constant-pool entry and trying to load from there. It's of doubtful benefit
267 // for A64: we'd need LDR followed by FCVT, I believe.
268 setLoadExtAction(ISD::EXTLOAD, MVT::f64, Expand);
269 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
270 setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
272 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
273 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
274 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
275 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
276 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
277 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
279 setExceptionPointerRegister(AArch64::X0);
280 setExceptionSelectorRegister(AArch64::X1);
282 if (Subtarget->hasNEON()) {
283 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i8, Custom);
284 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
285 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
286 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i16, Custom);
287 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
288 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
289 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i32, Custom);
290 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
291 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
292 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
293 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
294 setOperationAction(ISD::BUILD_VECTOR, MVT::v1f32, Custom);
295 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
296 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
297 setOperationAction(ISD::BUILD_VECTOR, MVT::v1f64, Custom);
298 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
300 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
301 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i16, Custom);
302 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
303 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i32, Custom);
304 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f32, Custom);
305 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
306 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1f64, Custom);
307 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
309 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Legal);
310 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Legal);
311 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Legal);
312 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f32, Legal);
313 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Legal);
315 setOperationAction(ISD::SETCC, MVT::v8i8, Custom);
316 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
317 setOperationAction(ISD::SETCC, MVT::v4i16, Custom);
318 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
319 setOperationAction(ISD::SETCC, MVT::v2i32, Custom);
320 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
321 setOperationAction(ISD::SETCC, MVT::v1i64, Custom);
322 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
323 setOperationAction(ISD::SETCC, MVT::v1f32, Custom);
324 setOperationAction(ISD::SETCC, MVT::v2f32, Custom);
325 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
326 setOperationAction(ISD::SETCC, MVT::v1f64, Custom);
327 setOperationAction(ISD::SETCC, MVT::v2f64, Custom);
331 EVT AArch64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
332 // It's reasonably important that this value matches the "natural" legal
333 // promotion from i1 for scalar types. Otherwise LegalizeTypes can get itself
334 // in a twist (e.g. inserting an any_extend which then becomes i64 -> i64).
335 if (!VT.isVector()) return MVT::i32;
336 return VT.changeVectorElementTypeToInteger();
339 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
342 static const unsigned LoadBares[] = {AArch64::LDXR_byte, AArch64::LDXR_hword,
343 AArch64::LDXR_word, AArch64::LDXR_dword};
344 static const unsigned LoadAcqs[] = {AArch64::LDAXR_byte, AArch64::LDAXR_hword,
345 AArch64::LDAXR_word, AArch64::LDAXR_dword};
346 static const unsigned StoreBares[] = {AArch64::STXR_byte, AArch64::STXR_hword,
347 AArch64::STXR_word, AArch64::STXR_dword};
348 static const unsigned StoreRels[] = {AArch64::STLXR_byte,AArch64::STLXR_hword,
349 AArch64::STLXR_word, AArch64::STLXR_dword};
351 const unsigned *LoadOps, *StoreOps;
352 if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
357 if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
358 StoreOps = StoreRels;
360 StoreOps = StoreBares;
362 assert(isPowerOf2_32(Size) && Size <= 8 &&
363 "unsupported size for atomic binary op!");
365 LdrOpc = LoadOps[Log2_32(Size)];
366 StrOpc = StoreOps[Log2_32(Size)];
370 AArch64TargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
372 unsigned BinOpcode) const {
373 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
374 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
376 const BasicBlock *LLVM_BB = BB->getBasicBlock();
377 MachineFunction *MF = BB->getParent();
378 MachineFunction::iterator It = BB;
381 unsigned dest = MI->getOperand(0).getReg();
382 unsigned ptr = MI->getOperand(1).getReg();
383 unsigned incr = MI->getOperand(2).getReg();
384 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
385 DebugLoc dl = MI->getDebugLoc();
387 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
389 unsigned ldrOpc, strOpc;
390 getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
392 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
393 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
394 MF->insert(It, loopMBB);
395 MF->insert(It, exitMBB);
397 // Transfer the remainder of BB and its successor edges to exitMBB.
398 exitMBB->splice(exitMBB->begin(), BB,
399 llvm::next(MachineBasicBlock::iterator(MI)),
401 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
403 const TargetRegisterClass *TRC
404 = Size == 8 ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
405 unsigned scratch = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
409 // fallthrough --> loopMBB
410 BB->addSuccessor(loopMBB);
414 // <binop> scratch, dest, incr
415 // stxr stxr_status, scratch, ptr
416 // cbnz stxr_status, loopMBB
417 // fallthrough --> exitMBB
419 BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
421 // All arithmetic operations we'll be creating are designed to take an extra
422 // shift or extend operand, which we can conveniently set to zero.
424 // Operand order needs to go the other way for NAND.
425 if (BinOpcode == AArch64::BICwww_lsl || BinOpcode == AArch64::BICxxx_lsl)
426 BuildMI(BB, dl, TII->get(BinOpcode), scratch)
427 .addReg(incr).addReg(dest).addImm(0);
429 BuildMI(BB, dl, TII->get(BinOpcode), scratch)
430 .addReg(dest).addReg(incr).addImm(0);
433 // From the stxr, the register is GPR32; from the cmp it's GPR32wsp
434 unsigned stxr_status = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
435 MRI.constrainRegClass(stxr_status, &AArch64::GPR32wspRegClass);
437 BuildMI(BB, dl, TII->get(strOpc), stxr_status).addReg(scratch).addReg(ptr);
438 BuildMI(BB, dl, TII->get(AArch64::CBNZw))
439 .addReg(stxr_status).addMBB(loopMBB);
441 BB->addSuccessor(loopMBB);
442 BB->addSuccessor(exitMBB);
448 MI->eraseFromParent(); // The instruction is gone now.
454 AArch64TargetLowering::emitAtomicBinaryMinMax(MachineInstr *MI,
455 MachineBasicBlock *BB,
458 A64CC::CondCodes Cond) const {
459 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
461 const BasicBlock *LLVM_BB = BB->getBasicBlock();
462 MachineFunction *MF = BB->getParent();
463 MachineFunction::iterator It = BB;
466 unsigned dest = MI->getOperand(0).getReg();
467 unsigned ptr = MI->getOperand(1).getReg();
468 unsigned incr = MI->getOperand(2).getReg();
469 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
471 unsigned oldval = dest;
472 DebugLoc dl = MI->getDebugLoc();
474 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
475 const TargetRegisterClass *TRC, *TRCsp;
477 TRC = &AArch64::GPR64RegClass;
478 TRCsp = &AArch64::GPR64xspRegClass;
480 TRC = &AArch64::GPR32RegClass;
481 TRCsp = &AArch64::GPR32wspRegClass;
484 unsigned ldrOpc, strOpc;
485 getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
487 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
488 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
489 MF->insert(It, loopMBB);
490 MF->insert(It, exitMBB);
492 // Transfer the remainder of BB and its successor edges to exitMBB.
493 exitMBB->splice(exitMBB->begin(), BB,
494 llvm::next(MachineBasicBlock::iterator(MI)),
496 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
498 unsigned scratch = MRI.createVirtualRegister(TRC);
499 MRI.constrainRegClass(scratch, TRCsp);
503 // fallthrough --> loopMBB
504 BB->addSuccessor(loopMBB);
508 // cmp incr, dest (, sign extend if necessary)
509 // csel scratch, dest, incr, cond
510 // stxr stxr_status, scratch, ptr
511 // cbnz stxr_status, loopMBB
512 // fallthrough --> exitMBB
514 BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
516 // Build compare and cmov instructions.
517 MRI.constrainRegClass(incr, TRCsp);
518 BuildMI(BB, dl, TII->get(CmpOp))
519 .addReg(incr).addReg(oldval).addImm(0);
521 BuildMI(BB, dl, TII->get(Size == 8 ? AArch64::CSELxxxc : AArch64::CSELwwwc),
523 .addReg(oldval).addReg(incr).addImm(Cond);
525 unsigned stxr_status = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
526 MRI.constrainRegClass(stxr_status, &AArch64::GPR32wspRegClass);
528 BuildMI(BB, dl, TII->get(strOpc), stxr_status)
529 .addReg(scratch).addReg(ptr);
530 BuildMI(BB, dl, TII->get(AArch64::CBNZw))
531 .addReg(stxr_status).addMBB(loopMBB);
533 BB->addSuccessor(loopMBB);
534 BB->addSuccessor(exitMBB);
540 MI->eraseFromParent(); // The instruction is gone now.
546 AArch64TargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
547 MachineBasicBlock *BB,
548 unsigned Size) const {
549 unsigned dest = MI->getOperand(0).getReg();
550 unsigned ptr = MI->getOperand(1).getReg();
551 unsigned oldval = MI->getOperand(2).getReg();
552 unsigned newval = MI->getOperand(3).getReg();
553 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
554 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
555 DebugLoc dl = MI->getDebugLoc();
557 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
558 const TargetRegisterClass *TRCsp;
559 TRCsp = Size == 8 ? &AArch64::GPR64xspRegClass : &AArch64::GPR32wspRegClass;
561 unsigned ldrOpc, strOpc;
562 getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
564 MachineFunction *MF = BB->getParent();
565 const BasicBlock *LLVM_BB = BB->getBasicBlock();
566 MachineFunction::iterator It = BB;
567 ++It; // insert the new blocks after the current block
569 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
570 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
571 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
572 MF->insert(It, loop1MBB);
573 MF->insert(It, loop2MBB);
574 MF->insert(It, exitMBB);
576 // Transfer the remainder of BB and its successor edges to exitMBB.
577 exitMBB->splice(exitMBB->begin(), BB,
578 llvm::next(MachineBasicBlock::iterator(MI)),
580 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
584 // fallthrough --> loop1MBB
585 BB->addSuccessor(loop1MBB);
592 BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
594 unsigned CmpOp = Size == 8 ? AArch64::CMPxx_lsl : AArch64::CMPww_lsl;
595 MRI.constrainRegClass(dest, TRCsp);
596 BuildMI(BB, dl, TII->get(CmpOp))
597 .addReg(dest).addReg(oldval).addImm(0);
598 BuildMI(BB, dl, TII->get(AArch64::Bcc))
599 .addImm(A64CC::NE).addMBB(exitMBB);
600 BB->addSuccessor(loop2MBB);
601 BB->addSuccessor(exitMBB);
604 // strex stxr_status, newval, [ptr]
605 // cbnz stxr_status, loop1MBB
607 unsigned stxr_status = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
608 MRI.constrainRegClass(stxr_status, &AArch64::GPR32wspRegClass);
610 BuildMI(BB, dl, TII->get(strOpc), stxr_status).addReg(newval).addReg(ptr);
611 BuildMI(BB, dl, TII->get(AArch64::CBNZw))
612 .addReg(stxr_status).addMBB(loop1MBB);
613 BB->addSuccessor(loop1MBB);
614 BB->addSuccessor(exitMBB);
620 MI->eraseFromParent(); // The instruction is gone now.
626 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
627 MachineBasicBlock *MBB) const {
628 // We materialise the F128CSEL pseudo-instruction using conditional branches
629 // and loads, giving an instruciton sequence like:
638 // Using virtual registers would probably not be beneficial since COPY
639 // instructions are expensive for f128 (there's no actual instruction to
642 // An alternative would be to do an integer-CSEL on some address. E.g.:
647 // csel x0, x0, x1, ne
650 // It's unclear which approach is actually optimal.
651 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
652 MachineFunction *MF = MBB->getParent();
653 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
654 DebugLoc DL = MI->getDebugLoc();
655 MachineFunction::iterator It = MBB;
658 unsigned DestReg = MI->getOperand(0).getReg();
659 unsigned IfTrueReg = MI->getOperand(1).getReg();
660 unsigned IfFalseReg = MI->getOperand(2).getReg();
661 unsigned CondCode = MI->getOperand(3).getImm();
662 bool NZCVKilled = MI->getOperand(4).isKill();
664 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
665 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
666 MF->insert(It, TrueBB);
667 MF->insert(It, EndBB);
669 // Transfer rest of current basic-block to EndBB
670 EndBB->splice(EndBB->begin(), MBB,
671 llvm::next(MachineBasicBlock::iterator(MI)),
673 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
675 // We need somewhere to store the f128 value needed.
676 int ScratchFI = MF->getFrameInfo()->CreateSpillStackObject(16, 16);
678 // [... start of incoming MBB ...]
679 // str qIFFALSE, [sp]
682 BuildMI(MBB, DL, TII->get(AArch64::LSFP128_STR))
684 .addFrameIndex(ScratchFI)
686 BuildMI(MBB, DL, TII->get(AArch64::Bcc))
689 BuildMI(MBB, DL, TII->get(AArch64::Bimm))
691 MBB->addSuccessor(TrueBB);
692 MBB->addSuccessor(EndBB);
696 BuildMI(TrueBB, DL, TII->get(AArch64::LSFP128_STR))
698 .addFrameIndex(ScratchFI)
701 // Note: fallthrough. We can rely on LLVM adding a branch if it reorders the
703 TrueBB->addSuccessor(EndBB);
707 // [... rest of incoming MBB ...]
709 EndBB->addLiveIn(AArch64::NZCV);
710 MachineInstr *StartOfEnd = EndBB->begin();
711 BuildMI(*EndBB, StartOfEnd, DL, TII->get(AArch64::LSFP128_LDR), DestReg)
712 .addFrameIndex(ScratchFI)
715 MI->eraseFromParent();
720 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
721 MachineBasicBlock *MBB) const {
722 switch (MI->getOpcode()) {
723 default: llvm_unreachable("Unhandled instruction with custom inserter");
724 case AArch64::F128CSEL:
725 return EmitF128CSEL(MI, MBB);
726 case AArch64::ATOMIC_LOAD_ADD_I8:
727 return emitAtomicBinary(MI, MBB, 1, AArch64::ADDwww_lsl);
728 case AArch64::ATOMIC_LOAD_ADD_I16:
729 return emitAtomicBinary(MI, MBB, 2, AArch64::ADDwww_lsl);
730 case AArch64::ATOMIC_LOAD_ADD_I32:
731 return emitAtomicBinary(MI, MBB, 4, AArch64::ADDwww_lsl);
732 case AArch64::ATOMIC_LOAD_ADD_I64:
733 return emitAtomicBinary(MI, MBB, 8, AArch64::ADDxxx_lsl);
735 case AArch64::ATOMIC_LOAD_SUB_I8:
736 return emitAtomicBinary(MI, MBB, 1, AArch64::SUBwww_lsl);
737 case AArch64::ATOMIC_LOAD_SUB_I16:
738 return emitAtomicBinary(MI, MBB, 2, AArch64::SUBwww_lsl);
739 case AArch64::ATOMIC_LOAD_SUB_I32:
740 return emitAtomicBinary(MI, MBB, 4, AArch64::SUBwww_lsl);
741 case AArch64::ATOMIC_LOAD_SUB_I64:
742 return emitAtomicBinary(MI, MBB, 8, AArch64::SUBxxx_lsl);
744 case AArch64::ATOMIC_LOAD_AND_I8:
745 return emitAtomicBinary(MI, MBB, 1, AArch64::ANDwww_lsl);
746 case AArch64::ATOMIC_LOAD_AND_I16:
747 return emitAtomicBinary(MI, MBB, 2, AArch64::ANDwww_lsl);
748 case AArch64::ATOMIC_LOAD_AND_I32:
749 return emitAtomicBinary(MI, MBB, 4, AArch64::ANDwww_lsl);
750 case AArch64::ATOMIC_LOAD_AND_I64:
751 return emitAtomicBinary(MI, MBB, 8, AArch64::ANDxxx_lsl);
753 case AArch64::ATOMIC_LOAD_OR_I8:
754 return emitAtomicBinary(MI, MBB, 1, AArch64::ORRwww_lsl);
755 case AArch64::ATOMIC_LOAD_OR_I16:
756 return emitAtomicBinary(MI, MBB, 2, AArch64::ORRwww_lsl);
757 case AArch64::ATOMIC_LOAD_OR_I32:
758 return emitAtomicBinary(MI, MBB, 4, AArch64::ORRwww_lsl);
759 case AArch64::ATOMIC_LOAD_OR_I64:
760 return emitAtomicBinary(MI, MBB, 8, AArch64::ORRxxx_lsl);
762 case AArch64::ATOMIC_LOAD_XOR_I8:
763 return emitAtomicBinary(MI, MBB, 1, AArch64::EORwww_lsl);
764 case AArch64::ATOMIC_LOAD_XOR_I16:
765 return emitAtomicBinary(MI, MBB, 2, AArch64::EORwww_lsl);
766 case AArch64::ATOMIC_LOAD_XOR_I32:
767 return emitAtomicBinary(MI, MBB, 4, AArch64::EORwww_lsl);
768 case AArch64::ATOMIC_LOAD_XOR_I64:
769 return emitAtomicBinary(MI, MBB, 8, AArch64::EORxxx_lsl);
771 case AArch64::ATOMIC_LOAD_NAND_I8:
772 return emitAtomicBinary(MI, MBB, 1, AArch64::BICwww_lsl);
773 case AArch64::ATOMIC_LOAD_NAND_I16:
774 return emitAtomicBinary(MI, MBB, 2, AArch64::BICwww_lsl);
775 case AArch64::ATOMIC_LOAD_NAND_I32:
776 return emitAtomicBinary(MI, MBB, 4, AArch64::BICwww_lsl);
777 case AArch64::ATOMIC_LOAD_NAND_I64:
778 return emitAtomicBinary(MI, MBB, 8, AArch64::BICxxx_lsl);
780 case AArch64::ATOMIC_LOAD_MIN_I8:
781 return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_sxtb, A64CC::GT);
782 case AArch64::ATOMIC_LOAD_MIN_I16:
783 return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_sxth, A64CC::GT);
784 case AArch64::ATOMIC_LOAD_MIN_I32:
785 return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::GT);
786 case AArch64::ATOMIC_LOAD_MIN_I64:
787 return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::GT);
789 case AArch64::ATOMIC_LOAD_MAX_I8:
790 return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_sxtb, A64CC::LT);
791 case AArch64::ATOMIC_LOAD_MAX_I16:
792 return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_sxth, A64CC::LT);
793 case AArch64::ATOMIC_LOAD_MAX_I32:
794 return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::LT);
795 case AArch64::ATOMIC_LOAD_MAX_I64:
796 return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::LT);
798 case AArch64::ATOMIC_LOAD_UMIN_I8:
799 return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_uxtb, A64CC::HI);
800 case AArch64::ATOMIC_LOAD_UMIN_I16:
801 return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_uxth, A64CC::HI);
802 case AArch64::ATOMIC_LOAD_UMIN_I32:
803 return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::HI);
804 case AArch64::ATOMIC_LOAD_UMIN_I64:
805 return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::HI);
807 case AArch64::ATOMIC_LOAD_UMAX_I8:
808 return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_uxtb, A64CC::LO);
809 case AArch64::ATOMIC_LOAD_UMAX_I16:
810 return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_uxth, A64CC::LO);
811 case AArch64::ATOMIC_LOAD_UMAX_I32:
812 return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::LO);
813 case AArch64::ATOMIC_LOAD_UMAX_I64:
814 return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::LO);
816 case AArch64::ATOMIC_SWAP_I8:
817 return emitAtomicBinary(MI, MBB, 1, 0);
818 case AArch64::ATOMIC_SWAP_I16:
819 return emitAtomicBinary(MI, MBB, 2, 0);
820 case AArch64::ATOMIC_SWAP_I32:
821 return emitAtomicBinary(MI, MBB, 4, 0);
822 case AArch64::ATOMIC_SWAP_I64:
823 return emitAtomicBinary(MI, MBB, 8, 0);
825 case AArch64::ATOMIC_CMP_SWAP_I8:
826 return emitAtomicCmpSwap(MI, MBB, 1);
827 case AArch64::ATOMIC_CMP_SWAP_I16:
828 return emitAtomicCmpSwap(MI, MBB, 2);
829 case AArch64::ATOMIC_CMP_SWAP_I32:
830 return emitAtomicCmpSwap(MI, MBB, 4);
831 case AArch64::ATOMIC_CMP_SWAP_I64:
832 return emitAtomicCmpSwap(MI, MBB, 8);
837 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
839 case AArch64ISD::BR_CC: return "AArch64ISD::BR_CC";
840 case AArch64ISD::Call: return "AArch64ISD::Call";
841 case AArch64ISD::FPMOV: return "AArch64ISD::FPMOV";
842 case AArch64ISD::GOTLoad: return "AArch64ISD::GOTLoad";
843 case AArch64ISD::BFI: return "AArch64ISD::BFI";
844 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
845 case AArch64ISD::Ret: return "AArch64ISD::Ret";
846 case AArch64ISD::SBFX: return "AArch64ISD::SBFX";
847 case AArch64ISD::SELECT_CC: return "AArch64ISD::SELECT_CC";
848 case AArch64ISD::SETCC: return "AArch64ISD::SETCC";
849 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
850 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
851 case AArch64ISD::TLSDESCCALL: return "AArch64ISD::TLSDESCCALL";
852 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
853 case AArch64ISD::WrapperSmall: return "AArch64ISD::WrapperSmall";
855 case AArch64ISD::NEON_BSL:
856 return "AArch64ISD::NEON_BSL";
857 case AArch64ISD::NEON_MOVIMM:
858 return "AArch64ISD::NEON_MOVIMM";
859 case AArch64ISD::NEON_MVNIMM:
860 return "AArch64ISD::NEON_MVNIMM";
861 case AArch64ISD::NEON_FMOVIMM:
862 return "AArch64ISD::NEON_FMOVIMM";
863 case AArch64ISD::NEON_CMP:
864 return "AArch64ISD::NEON_CMP";
865 case AArch64ISD::NEON_CMPZ:
866 return "AArch64ISD::NEON_CMPZ";
867 case AArch64ISD::NEON_TST:
868 return "AArch64ISD::NEON_TST";
869 case AArch64ISD::NEON_DUPIMM:
870 return "AArch64ISD::NEON_DUPIMM";
871 case AArch64ISD::NEON_QSHLs:
872 return "AArch64ISD::NEON_QSHLs";
873 case AArch64ISD::NEON_QSHLu:
874 return "AArch64ISD::NEON_QSHLu";
875 case AArch64ISD::NEON_VDUPLANE:
876 return "AArch64ISD::NEON_VDUPLANE";
882 static const uint16_t AArch64FPRArgRegs[] = {
883 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
884 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7
886 static const unsigned NumFPRArgRegs = llvm::array_lengthof(AArch64FPRArgRegs);
888 static const uint16_t AArch64ArgRegs[] = {
889 AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3,
890 AArch64::X4, AArch64::X5, AArch64::X6, AArch64::X7
892 static const unsigned NumArgRegs = llvm::array_lengthof(AArch64ArgRegs);
894 static bool CC_AArch64NoMoreRegs(unsigned ValNo, MVT ValVT, MVT LocVT,
895 CCValAssign::LocInfo LocInfo,
896 ISD::ArgFlagsTy ArgFlags, CCState &State) {
897 // Mark all remaining general purpose registers as allocated. We don't
898 // backtrack: if (for example) an i128 gets put on the stack, no subsequent
899 // i64 will go in registers (C.11).
900 for (unsigned i = 0; i < NumArgRegs; ++i)
901 State.AllocateReg(AArch64ArgRegs[i]);
906 #include "AArch64GenCallingConv.inc"
908 CCAssignFn *AArch64TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
911 default: llvm_unreachable("Unsupported calling convention");
912 case CallingConv::Fast:
919 AArch64TargetLowering::SaveVarArgRegisters(CCState &CCInfo, SelectionDAG &DAG,
920 SDLoc DL, SDValue &Chain) const {
921 MachineFunction &MF = DAG.getMachineFunction();
922 MachineFrameInfo *MFI = MF.getFrameInfo();
923 AArch64MachineFunctionInfo *FuncInfo
924 = MF.getInfo<AArch64MachineFunctionInfo>();
926 SmallVector<SDValue, 8> MemOps;
928 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(AArch64ArgRegs,
930 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(AArch64FPRArgRegs,
933 unsigned GPRSaveSize = 8 * (NumArgRegs - FirstVariadicGPR);
935 if (GPRSaveSize != 0) {
936 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
938 SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
940 for (unsigned i = FirstVariadicGPR; i < NumArgRegs; ++i) {
941 unsigned VReg = MF.addLiveIn(AArch64ArgRegs[i], &AArch64::GPR64RegClass);
942 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
943 SDValue Store = DAG.getStore(Val.getValue(1), DL, Val, FIN,
944 MachinePointerInfo::getStack(i * 8),
946 MemOps.push_back(Store);
947 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
948 DAG.getConstant(8, getPointerTy()));
952 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
954 if (FPRSaveSize != 0) {
955 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
957 SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
959 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
960 unsigned VReg = MF.addLiveIn(AArch64FPRArgRegs[i],
961 &AArch64::FPR128RegClass);
962 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
963 SDValue Store = DAG.getStore(Val.getValue(1), DL, Val, FIN,
964 MachinePointerInfo::getStack(i * 16),
966 MemOps.push_back(Store);
967 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
968 DAG.getConstant(16, getPointerTy()));
972 int StackIdx = MFI->CreateFixedObject(8, CCInfo.getNextStackOffset(), true);
974 FuncInfo->setVariadicStackIdx(StackIdx);
975 FuncInfo->setVariadicGPRIdx(GPRIdx);
976 FuncInfo->setVariadicGPRSize(GPRSaveSize);
977 FuncInfo->setVariadicFPRIdx(FPRIdx);
978 FuncInfo->setVariadicFPRSize(FPRSaveSize);
980 if (!MemOps.empty()) {
981 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
988 AArch64TargetLowering::LowerFormalArguments(SDValue Chain,
989 CallingConv::ID CallConv, bool isVarArg,
990 const SmallVectorImpl<ISD::InputArg> &Ins,
991 SDLoc dl, SelectionDAG &DAG,
992 SmallVectorImpl<SDValue> &InVals) const {
993 MachineFunction &MF = DAG.getMachineFunction();
994 AArch64MachineFunctionInfo *FuncInfo
995 = MF.getInfo<AArch64MachineFunctionInfo>();
996 MachineFrameInfo *MFI = MF.getFrameInfo();
997 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
999 SmallVector<CCValAssign, 16> ArgLocs;
1000 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1001 getTargetMachine(), ArgLocs, *DAG.getContext());
1002 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1004 SmallVector<SDValue, 16> ArgValues;
1007 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1008 CCValAssign &VA = ArgLocs[i];
1009 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1011 if (Flags.isByVal()) {
1012 // Byval is used for small structs and HFAs in the PCS, but the system
1013 // should work in a non-compliant manner for larger structs.
1014 EVT PtrTy = getPointerTy();
1015 int Size = Flags.getByValSize();
1016 unsigned NumRegs = (Size + 7) / 8;
1018 unsigned FrameIdx = MFI->CreateFixedObject(8 * NumRegs,
1019 VA.getLocMemOffset(),
1021 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrTy);
1022 InVals.push_back(FrameIdxN);
1025 } else if (VA.isRegLoc()) {
1026 MVT RegVT = VA.getLocVT();
1027 const TargetRegisterClass *RC = getRegClassFor(RegVT);
1028 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1030 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1031 } else { // VA.isRegLoc()
1032 assert(VA.isMemLoc());
1034 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
1035 VA.getLocMemOffset(), true);
1037 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1038 ArgValue = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1039 MachinePointerInfo::getFixedStack(FI),
1040 false, false, false, 0);
1045 switch (VA.getLocInfo()) {
1046 default: llvm_unreachable("Unknown loc info!");
1047 case CCValAssign::Full: break;
1048 case CCValAssign::BCvt:
1049 ArgValue = DAG.getNode(ISD::BITCAST,dl, VA.getValVT(), ArgValue);
1051 case CCValAssign::SExt:
1052 case CCValAssign::ZExt:
1053 case CCValAssign::AExt: {
1054 unsigned DestSize = VA.getValVT().getSizeInBits();
1055 unsigned DestSubReg;
1058 case 8: DestSubReg = AArch64::sub_8; break;
1059 case 16: DestSubReg = AArch64::sub_16; break;
1060 case 32: DestSubReg = AArch64::sub_32; break;
1061 case 64: DestSubReg = AArch64::sub_64; break;
1062 default: llvm_unreachable("Unexpected argument promotion");
1065 ArgValue = SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl,
1066 VA.getValVT(), ArgValue,
1067 DAG.getTargetConstant(DestSubReg, MVT::i32)),
1073 InVals.push_back(ArgValue);
1077 SaveVarArgRegisters(CCInfo, DAG, dl, Chain);
1079 unsigned StackArgSize = CCInfo.getNextStackOffset();
1080 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
1081 // This is a non-standard ABI so by fiat I say we're allowed to make full
1082 // use of the stack area to be popped, which must be aligned to 16 bytes in
1084 StackArgSize = RoundUpToAlignment(StackArgSize, 16);
1086 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
1087 // a multiple of 16.
1088 FuncInfo->setArgumentStackToRestore(StackArgSize);
1090 // This realignment carries over to the available bytes below. Our own
1091 // callers will guarantee the space is free by giving an aligned value to
1094 // Even if we're not expected to free up the space, it's useful to know how
1095 // much is there while considering tail calls (because we can reuse it).
1096 FuncInfo->setBytesInStackArgArea(StackArgSize);
1102 AArch64TargetLowering::LowerReturn(SDValue Chain,
1103 CallingConv::ID CallConv, bool isVarArg,
1104 const SmallVectorImpl<ISD::OutputArg> &Outs,
1105 const SmallVectorImpl<SDValue> &OutVals,
1106 SDLoc dl, SelectionDAG &DAG) const {
1107 // CCValAssign - represent the assignment of the return value to a location.
1108 SmallVector<CCValAssign, 16> RVLocs;
1110 // CCState - Info about the registers and stack slots.
1111 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1112 getTargetMachine(), RVLocs, *DAG.getContext());
1114 // Analyze outgoing return values.
1115 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv));
1118 SmallVector<SDValue, 4> RetOps(1, Chain);
1120 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1121 // PCS: "If the type, T, of the result of a function is such that
1122 // void func(T arg) would require that arg be passed as a value in a
1123 // register (or set of registers) according to the rules in 5.4, then the
1124 // result is returned in the same registers as would be used for such an
1127 // Otherwise, the caller shall reserve a block of memory of sufficient
1128 // size and alignment to hold the result. The address of the memory block
1129 // shall be passed as an additional argument to the function in x8."
1131 // This is implemented in two places. The register-return values are dealt
1132 // with here, more complex returns are passed as an sret parameter, which
1133 // means we don't have to worry about it during actual return.
1134 CCValAssign &VA = RVLocs[i];
1135 assert(VA.isRegLoc() && "Only register-returns should be created by PCS");
1138 SDValue Arg = OutVals[i];
1140 // There's no convenient note in the ABI about this as there is for normal
1141 // arguments, but it says return values are passed in the same registers as
1142 // an argument would be. I believe that includes the comments about
1143 // unspecified higher bits, putting the burden of widening on the *caller*
1144 // for return values.
1145 switch (VA.getLocInfo()) {
1146 default: llvm_unreachable("Unknown loc info");
1147 case CCValAssign::Full: break;
1148 case CCValAssign::SExt:
1149 case CCValAssign::ZExt:
1150 case CCValAssign::AExt:
1151 // Floating-point values should only be extended when they're going into
1152 // memory, which can't happen here so an integer extend is acceptable.
1153 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1155 case CCValAssign::BCvt:
1156 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1160 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1161 Flag = Chain.getValue(1);
1162 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1165 RetOps[0] = Chain; // Update chain.
1167 // Add the flag if we have it.
1169 RetOps.push_back(Flag);
1171 return DAG.getNode(AArch64ISD::Ret, dl, MVT::Other,
1172 &RetOps[0], RetOps.size());
1176 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
1177 SmallVectorImpl<SDValue> &InVals) const {
1178 SelectionDAG &DAG = CLI.DAG;
1180 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1181 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1182 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1183 SDValue Chain = CLI.Chain;
1184 SDValue Callee = CLI.Callee;
1185 bool &IsTailCall = CLI.IsTailCall;
1186 CallingConv::ID CallConv = CLI.CallConv;
1187 bool IsVarArg = CLI.IsVarArg;
1189 MachineFunction &MF = DAG.getMachineFunction();
1190 AArch64MachineFunctionInfo *FuncInfo
1191 = MF.getInfo<AArch64MachineFunctionInfo>();
1192 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
1193 bool IsStructRet = !Outs.empty() && Outs[0].Flags.isSRet();
1194 bool IsSibCall = false;
1197 IsTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1198 IsVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1199 Outs, OutVals, Ins, DAG);
1201 // A sibling call is one where we're under the usual C ABI and not planning
1202 // to change that but can still do a tail call:
1203 if (!TailCallOpt && IsTailCall)
1207 SmallVector<CCValAssign, 16> ArgLocs;
1208 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
1209 getTargetMachine(), ArgLocs, *DAG.getContext());
1210 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1212 // On AArch64 (and all other architectures I'm aware of) the most this has to
1213 // do is adjust the stack pointer.
1214 unsigned NumBytes = RoundUpToAlignment(CCInfo.getNextStackOffset(), 16);
1216 // Since we're not changing the ABI to make this a tail call, the memory
1217 // operands are already available in the caller's incoming argument space.
1221 // FPDiff is the byte offset of the call's argument area from the callee's.
1222 // Stores to callee stack arguments will be placed in FixedStackSlots offset
1223 // by this amount for a tail call. In a sibling call it must be 0 because the
1224 // caller will deallocate the entire stack and the callee still expects its
1225 // arguments to begin at SP+0. Completely unused for non-tail calls.
1228 if (IsTailCall && !IsSibCall) {
1229 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
1231 // FPDiff will be negative if this tail call requires more space than we
1232 // would automatically have in our incoming argument space. Positive if we
1233 // can actually shrink the stack.
1234 FPDiff = NumReusableBytes - NumBytes;
1236 // The stack pointer must be 16-byte aligned at all times it's used for a
1237 // memory operation, which in practice means at *all* times and in
1238 // particular across call boundaries. Therefore our own arguments started at
1239 // a 16-byte aligned SP and the delta applied for the tail call should
1240 // satisfy the same constraint.
1241 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
1245 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1248 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, AArch64::XSP,
1251 SmallVector<SDValue, 8> MemOpChains;
1252 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1254 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1255 CCValAssign &VA = ArgLocs[i];
1256 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1257 SDValue Arg = OutVals[i];
1259 // Callee does the actual widening, so all extensions just use an implicit
1260 // definition of the rest of the Loc. Aesthetically, this would be nicer as
1261 // an ANY_EXTEND, but that isn't valid for floating-point types and this
1262 // alternative works on integer types too.
1263 switch (VA.getLocInfo()) {
1264 default: llvm_unreachable("Unknown loc info!");
1265 case CCValAssign::Full: break;
1266 case CCValAssign::SExt:
1267 case CCValAssign::ZExt:
1268 case CCValAssign::AExt: {
1269 unsigned SrcSize = VA.getValVT().getSizeInBits();
1273 case 8: SrcSubReg = AArch64::sub_8; break;
1274 case 16: SrcSubReg = AArch64::sub_16; break;
1275 case 32: SrcSubReg = AArch64::sub_32; break;
1276 case 64: SrcSubReg = AArch64::sub_64; break;
1277 default: llvm_unreachable("Unexpected argument promotion");
1280 Arg = SDValue(DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl,
1282 DAG.getUNDEF(VA.getLocVT()),
1284 DAG.getTargetConstant(SrcSubReg, MVT::i32)),
1289 case CCValAssign::BCvt:
1290 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1294 if (VA.isRegLoc()) {
1295 // A normal register (sub-) argument. For now we just note it down because
1296 // we want to copy things into registers as late as possible to avoid
1297 // register-pressure (and possibly worse).
1298 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1302 assert(VA.isMemLoc() && "unexpected argument location");
1305 MachinePointerInfo DstInfo;
1307 uint32_t OpSize = Flags.isByVal() ? Flags.getByValSize() :
1308 VA.getLocVT().getSizeInBits();
1309 OpSize = (OpSize + 7) / 8;
1310 int32_t Offset = VA.getLocMemOffset() + FPDiff;
1311 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
1313 DstAddr = DAG.getFrameIndex(FI, getPointerTy());
1314 DstInfo = MachinePointerInfo::getFixedStack(FI);
1316 // Make sure any stack arguments overlapping with where we're storing are
1317 // loaded before this eventual operation. Otherwise they'll be clobbered.
1318 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
1320 SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset());
1322 DstAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1323 DstInfo = MachinePointerInfo::getStack(VA.getLocMemOffset());
1326 if (Flags.isByVal()) {
1327 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i64);
1328 SDValue Cpy = DAG.getMemcpy(Chain, dl, DstAddr, Arg, SizeNode,
1329 Flags.getByValAlign(),
1330 /*isVolatile = */ false,
1331 /*alwaysInline = */ false,
1332 DstInfo, MachinePointerInfo(0));
1333 MemOpChains.push_back(Cpy);
1335 // Normal stack argument, put it where it's needed.
1336 SDValue Store = DAG.getStore(Chain, dl, Arg, DstAddr, DstInfo,
1338 MemOpChains.push_back(Store);
1342 // The loads and stores generated above shouldn't clash with each
1343 // other. Combining them with this TokenFactor notes that fact for the rest of
1345 if (!MemOpChains.empty())
1346 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1347 &MemOpChains[0], MemOpChains.size());
1349 // Most of the rest of the instructions need to be glued together; we don't
1350 // want assignments to actual registers used by a call to be rearranged by a
1351 // well-meaning scheduler.
1354 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1355 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1356 RegsToPass[i].second, InFlag);
1357 InFlag = Chain.getValue(1);
1360 // The linker is responsible for inserting veneers when necessary to put a
1361 // function call destination in range, so we don't need to bother with a
1363 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1364 const GlobalValue *GV = G->getGlobal();
1365 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy());
1366 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1367 const char *Sym = S->getSymbol();
1368 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy());
1371 // We don't usually want to end the call-sequence here because we would tidy
1372 // the frame up *after* the call, however in the ABI-changing tail-call case
1373 // we've carefully laid out the parameters so that when sp is reset they'll be
1374 // in the correct location.
1375 if (IsTailCall && !IsSibCall) {
1376 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1377 DAG.getIntPtrConstant(0, true), InFlag, dl);
1378 InFlag = Chain.getValue(1);
1381 // We produce the following DAG scheme for the actual call instruction:
1382 // (AArch64Call Chain, Callee, reg1, ..., regn, preserveMask, inflag?
1384 // Most arguments aren't going to be used and just keep the values live as
1385 // far as LLVM is concerned. It's expected to be selected as simply "bl
1386 // callee" (for a direct, non-tail call).
1387 std::vector<SDValue> Ops;
1388 Ops.push_back(Chain);
1389 Ops.push_back(Callee);
1392 // Each tail call may have to adjust the stack by a different amount, so
1393 // this information must travel along with the operation for eventual
1394 // consumption by emitEpilogue.
1395 Ops.push_back(DAG.getTargetConstant(FPDiff, MVT::i32));
1398 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1399 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1400 RegsToPass[i].second.getValueType()));
1403 // Add a register mask operand representing the call-preserved registers. This
1404 // is used later in codegen to constrain register-allocation.
1405 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1406 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1407 assert(Mask && "Missing call preserved mask for calling convention");
1408 Ops.push_back(DAG.getRegisterMask(Mask));
1410 // If we needed glue, put it in as the last argument.
1411 if (InFlag.getNode())
1412 Ops.push_back(InFlag);
1414 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1417 return DAG.getNode(AArch64ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1420 Chain = DAG.getNode(AArch64ISD::Call, dl, NodeTys, &Ops[0], Ops.size());
1421 InFlag = Chain.getValue(1);
1423 // Now we can reclaim the stack, just as well do it before working out where
1424 // our return value is.
1426 uint64_t CalleePopBytes
1427 = DoesCalleeRestoreStack(CallConv, TailCallOpt) ? NumBytes : 0;
1429 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1430 DAG.getIntPtrConstant(CalleePopBytes, true),
1432 InFlag = Chain.getValue(1);
1435 return LowerCallResult(Chain, InFlag, CallConv,
1436 IsVarArg, Ins, dl, DAG, InVals);
1440 AArch64TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1441 CallingConv::ID CallConv, bool IsVarArg,
1442 const SmallVectorImpl<ISD::InputArg> &Ins,
1443 SDLoc dl, SelectionDAG &DAG,
1444 SmallVectorImpl<SDValue> &InVals) const {
1445 // Assign locations to each value returned by this call.
1446 SmallVector<CCValAssign, 16> RVLocs;
1447 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
1448 getTargetMachine(), RVLocs, *DAG.getContext());
1449 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForNode(CallConv));
1451 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1452 CCValAssign VA = RVLocs[i];
1454 // Return values that are too big to fit into registers should use an sret
1455 // pointer, so this can be a lot simpler than the main argument code.
1456 assert(VA.isRegLoc() && "Memory locations not expected for call return");
1458 SDValue Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1460 Chain = Val.getValue(1);
1461 InFlag = Val.getValue(2);
1463 switch (VA.getLocInfo()) {
1464 default: llvm_unreachable("Unknown loc info!");
1465 case CCValAssign::Full: break;
1466 case CCValAssign::BCvt:
1467 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1469 case CCValAssign::ZExt:
1470 case CCValAssign::SExt:
1471 case CCValAssign::AExt:
1472 // Floating-point arguments only get extended/truncated if they're going
1473 // in memory, so using the integer operation is acceptable here.
1474 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
1478 InVals.push_back(Val);
1485 AArch64TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1486 CallingConv::ID CalleeCC,
1488 bool IsCalleeStructRet,
1489 bool IsCallerStructRet,
1490 const SmallVectorImpl<ISD::OutputArg> &Outs,
1491 const SmallVectorImpl<SDValue> &OutVals,
1492 const SmallVectorImpl<ISD::InputArg> &Ins,
1493 SelectionDAG& DAG) const {
1495 // For CallingConv::C this function knows whether the ABI needs
1496 // changing. That's not true for other conventions so they will have to opt in
1498 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1501 const MachineFunction &MF = DAG.getMachineFunction();
1502 const Function *CallerF = MF.getFunction();
1503 CallingConv::ID CallerCC = CallerF->getCallingConv();
1504 bool CCMatch = CallerCC == CalleeCC;
1506 // Byval parameters hand the function a pointer directly into the stack area
1507 // we want to reuse during a tail call. Working around this *is* possible (see
1508 // X86) but less efficient and uglier in LowerCall.
1509 for (Function::const_arg_iterator i = CallerF->arg_begin(),
1510 e = CallerF->arg_end(); i != e; ++i)
1511 if (i->hasByValAttr())
1514 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
1515 if (IsTailCallConvention(CalleeCC) && CCMatch)
1520 // Now we search for cases where we can use a tail call without changing the
1521 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
1524 // I want anyone implementing a new calling convention to think long and hard
1525 // about this assert.
1526 assert((!IsVarArg || CalleeCC == CallingConv::C)
1527 && "Unexpected variadic calling convention");
1529 if (IsVarArg && !Outs.empty()) {
1530 // At least two cases here: if caller is fastcc then we can't have any
1531 // memory arguments (we'd be expected to clean up the stack afterwards). If
1532 // caller is C then we could potentially use its argument area.
1534 // FIXME: for now we take the most conservative of these in both cases:
1535 // disallow all variadic memory operands.
1536 SmallVector<CCValAssign, 16> ArgLocs;
1537 CCState CCInfo(CalleeCC, IsVarArg, DAG.getMachineFunction(),
1538 getTargetMachine(), ArgLocs, *DAG.getContext());
1540 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
1541 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
1542 if (!ArgLocs[i].isRegLoc())
1546 // If the calling conventions do not match, then we'd better make sure the
1547 // results are returned in the same way as what the caller expects.
1549 SmallVector<CCValAssign, 16> RVLocs1;
1550 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1551 getTargetMachine(), RVLocs1, *DAG.getContext());
1552 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC));
1554 SmallVector<CCValAssign, 16> RVLocs2;
1555 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1556 getTargetMachine(), RVLocs2, *DAG.getContext());
1557 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC));
1559 if (RVLocs1.size() != RVLocs2.size())
1561 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1562 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1564 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1566 if (RVLocs1[i].isRegLoc()) {
1567 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1570 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1576 // Nothing more to check if the callee is taking no arguments
1580 SmallVector<CCValAssign, 16> ArgLocs;
1581 CCState CCInfo(CalleeCC, IsVarArg, DAG.getMachineFunction(),
1582 getTargetMachine(), ArgLocs, *DAG.getContext());
1584 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
1586 const AArch64MachineFunctionInfo *FuncInfo
1587 = MF.getInfo<AArch64MachineFunctionInfo>();
1589 // If the stack arguments for this call would fit into our own save area then
1590 // the call can be made tail.
1591 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
1594 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
1595 bool TailCallOpt) const {
1596 return CallCC == CallingConv::Fast && TailCallOpt;
1599 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
1600 return CallCC == CallingConv::Fast;
1603 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
1605 MachineFrameInfo *MFI,
1606 int ClobberedFI) const {
1607 SmallVector<SDValue, 8> ArgChains;
1608 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
1609 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
1611 // Include the original chain at the beginning of the list. When this is
1612 // used by target LowerCall hooks, this helps legalize find the
1613 // CALLSEQ_BEGIN node.
1614 ArgChains.push_back(Chain);
1616 // Add a chain value for each stack argument corresponding
1617 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
1618 UE = DAG.getEntryNode().getNode()->use_end(); U != UE; ++U)
1619 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
1620 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
1621 if (FI->getIndex() < 0) {
1622 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
1623 int64_t InLastByte = InFirstByte;
1624 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
1626 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
1627 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
1628 ArgChains.push_back(SDValue(L, 1));
1631 // Build a tokenfactor for all the chains.
1632 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other,
1633 &ArgChains[0], ArgChains.size());
1636 static A64CC::CondCodes IntCCToA64CC(ISD::CondCode CC) {
1638 case ISD::SETEQ: return A64CC::EQ;
1639 case ISD::SETGT: return A64CC::GT;
1640 case ISD::SETGE: return A64CC::GE;
1641 case ISD::SETLT: return A64CC::LT;
1642 case ISD::SETLE: return A64CC::LE;
1643 case ISD::SETNE: return A64CC::NE;
1644 case ISD::SETUGT: return A64CC::HI;
1645 case ISD::SETUGE: return A64CC::HS;
1646 case ISD::SETULT: return A64CC::LO;
1647 case ISD::SETULE: return A64CC::LS;
1648 default: llvm_unreachable("Unexpected condition code");
1652 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Val) const {
1653 // icmp is implemented using adds/subs immediate, which take an unsigned
1654 // 12-bit immediate, optionally shifted left by 12 bits.
1656 // Symmetric by using adds/subs
1660 return (Val & ~0xfff) == 0 || (Val & ~0xfff000) == 0;
1663 SDValue AArch64TargetLowering::getSelectableIntSetCC(SDValue LHS, SDValue RHS,
1664 ISD::CondCode CC, SDValue &A64cc,
1665 SelectionDAG &DAG, SDLoc &dl) const {
1666 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1668 EVT VT = RHSC->getValueType(0);
1669 bool knownInvalid = false;
1671 // I'm not convinced the rest of LLVM handles these edge cases properly, but
1672 // we can at least get it right.
1673 if (isSignedIntSetCC(CC)) {
1674 C = RHSC->getSExtValue();
1675 } else if (RHSC->getZExtValue() > INT64_MAX) {
1676 // A 64-bit constant not representable by a signed 64-bit integer is far
1677 // too big to fit into a SUBS immediate anyway.
1678 knownInvalid = true;
1680 C = RHSC->getZExtValue();
1683 if (!knownInvalid && !isLegalICmpImmediate(C)) {
1684 // Constant does not fit, try adjusting it by one?
1689 if (isLegalICmpImmediate(C-1)) {
1690 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1691 RHS = DAG.getConstant(C-1, VT);
1696 if (isLegalICmpImmediate(C-1)) {
1697 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1698 RHS = DAG.getConstant(C-1, VT);
1703 if (isLegalICmpImmediate(C+1)) {
1704 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1705 RHS = DAG.getConstant(C+1, VT);
1710 if (isLegalICmpImmediate(C+1)) {
1711 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1712 RHS = DAG.getConstant(C+1, VT);
1719 A64CC::CondCodes CondCode = IntCCToA64CC(CC);
1720 A64cc = DAG.getConstant(CondCode, MVT::i32);
1721 return DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
1722 DAG.getCondCode(CC));
1725 static A64CC::CondCodes FPCCToA64CC(ISD::CondCode CC,
1726 A64CC::CondCodes &Alternative) {
1727 A64CC::CondCodes CondCode = A64CC::Invalid;
1728 Alternative = A64CC::Invalid;
1731 default: llvm_unreachable("Unknown FP condition!");
1733 case ISD::SETOEQ: CondCode = A64CC::EQ; break;
1735 case ISD::SETOGT: CondCode = A64CC::GT; break;
1737 case ISD::SETOGE: CondCode = A64CC::GE; break;
1738 case ISD::SETOLT: CondCode = A64CC::MI; break;
1739 case ISD::SETOLE: CondCode = A64CC::LS; break;
1740 case ISD::SETONE: CondCode = A64CC::MI; Alternative = A64CC::GT; break;
1741 case ISD::SETO: CondCode = A64CC::VC; break;
1742 case ISD::SETUO: CondCode = A64CC::VS; break;
1743 case ISD::SETUEQ: CondCode = A64CC::EQ; Alternative = A64CC::VS; break;
1744 case ISD::SETUGT: CondCode = A64CC::HI; break;
1745 case ISD::SETUGE: CondCode = A64CC::PL; break;
1747 case ISD::SETULT: CondCode = A64CC::LT; break;
1749 case ISD::SETULE: CondCode = A64CC::LE; break;
1751 case ISD::SETUNE: CondCode = A64CC::NE; break;
1757 AArch64TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
1759 EVT PtrVT = getPointerTy();
1760 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1762 switch(getTargetMachine().getCodeModel()) {
1763 case CodeModel::Small:
1764 // The most efficient code is PC-relative anyway for the small memory model,
1765 // so we don't need to worry about relocation model.
1766 return DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
1767 DAG.getTargetBlockAddress(BA, PtrVT, 0,
1768 AArch64II::MO_NO_FLAG),
1769 DAG.getTargetBlockAddress(BA, PtrVT, 0,
1770 AArch64II::MO_LO12),
1771 DAG.getConstant(/*Alignment=*/ 4, MVT::i32));
1772 case CodeModel::Large:
1774 AArch64ISD::WrapperLarge, DL, PtrVT,
1775 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G3),
1776 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G2_NC),
1777 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G1_NC),
1778 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G0_NC));
1780 llvm_unreachable("Only small and large code models supported now");
1785 // (BRCOND chain, val, dest)
1787 AArch64TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1789 SDValue Chain = Op.getOperand(0);
1790 SDValue TheBit = Op.getOperand(1);
1791 SDValue DestBB = Op.getOperand(2);
1793 // AArch64 BooleanContents is the default UndefinedBooleanContent, which means
1794 // that as the consumer we are responsible for ignoring rubbish in higher
1796 TheBit = DAG.getNode(ISD::AND, dl, MVT::i32, TheBit,
1797 DAG.getConstant(1, MVT::i32));
1799 SDValue A64CMP = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, TheBit,
1800 DAG.getConstant(0, TheBit.getValueType()),
1801 DAG.getCondCode(ISD::SETNE));
1803 return DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other, Chain,
1804 A64CMP, DAG.getConstant(A64CC::NE, MVT::i32),
1808 // (BR_CC chain, condcode, lhs, rhs, dest)
1810 AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
1812 SDValue Chain = Op.getOperand(0);
1813 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1814 SDValue LHS = Op.getOperand(2);
1815 SDValue RHS = Op.getOperand(3);
1816 SDValue DestBB = Op.getOperand(4);
1818 if (LHS.getValueType() == MVT::f128) {
1819 // f128 comparisons are lowered to runtime calls by a routine which sets
1820 // LHS, RHS and CC appropriately for the rest of this function to continue.
1821 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
1823 // If softenSetCCOperands returned a scalar, we need to compare the result
1824 // against zero to select between true and false values.
1825 if (RHS.getNode() == 0) {
1826 RHS = DAG.getConstant(0, LHS.getValueType());
1831 if (LHS.getValueType().isInteger()) {
1834 // Integers are handled in a separate function because the combinations of
1835 // immediates and tests can get hairy and we may want to fiddle things.
1836 SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
1838 return DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
1839 Chain, CmpOp, A64cc, DestBB);
1842 // Note that some LLVM floating-point CondCodes can't be lowered to a single
1843 // conditional branch, hence FPCCToA64CC can set a second test, where either
1844 // passing is sufficient.
1845 A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
1846 CondCode = FPCCToA64CC(CC, Alternative);
1847 SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
1848 SDValue SetCC = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
1849 DAG.getCondCode(CC));
1850 SDValue A64BR_CC = DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
1851 Chain, SetCC, A64cc, DestBB);
1853 if (Alternative != A64CC::Invalid) {
1854 A64cc = DAG.getConstant(Alternative, MVT::i32);
1855 A64BR_CC = DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
1856 A64BR_CC, SetCC, A64cc, DestBB);
1864 AArch64TargetLowering::LowerF128ToCall(SDValue Op, SelectionDAG &DAG,
1865 RTLIB::Libcall Call) const {
1868 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
1869 EVT ArgVT = Op.getOperand(i).getValueType();
1870 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1871 Entry.Node = Op.getOperand(i); Entry.Ty = ArgTy;
1872 Entry.isSExt = false;
1873 Entry.isZExt = false;
1874 Args.push_back(Entry);
1876 SDValue Callee = DAG.getExternalSymbol(getLibcallName(Call), getPointerTy());
1878 Type *RetTy = Op.getValueType().getTypeForEVT(*DAG.getContext());
1880 // By default, the input chain to this libcall is the entry node of the
1881 // function. If the libcall is going to be emitted as a tail call then
1882 // isUsedByReturnOnly will change it to the right chain if the return
1883 // node which is being folded has a non-entry input chain.
1884 SDValue InChain = DAG.getEntryNode();
1886 // isTailCall may be true since the callee does not reference caller stack
1887 // frame. Check if it's in the right position.
1888 SDValue TCChain = InChain;
1889 bool isTailCall = isInTailCallPosition(DAG, Op.getNode(), TCChain);
1894 CallLoweringInfo CLI(InChain, RetTy, false, false, false, false,
1895 0, getLibcallCallingConv(Call), isTailCall,
1896 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
1897 Callee, Args, DAG, SDLoc(Op));
1898 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
1900 if (!CallInfo.second.getNode())
1901 // It's a tailcall, return the chain (which is the DAG root).
1902 return DAG.getRoot();
1904 return CallInfo.first;
1908 AArch64TargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
1909 if (Op.getOperand(0).getValueType() != MVT::f128) {
1910 // It's legal except when f128 is involved
1915 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1917 SDValue SrcVal = Op.getOperand(0);
1918 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1919 /*isSigned*/ false, SDLoc(Op)).first;
1923 AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
1924 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1927 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1929 return LowerF128ToCall(Op, DAG, LC);
1933 AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
1934 bool IsSigned) const {
1935 if (Op.getOperand(0).getValueType() != MVT::f128) {
1936 // It's legal except when f128 is involved
1942 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1944 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1946 return LowerF128ToCall(Op, DAG, LC);
1950 AArch64TargetLowering::LowerGlobalAddressELFLarge(SDValue Op,
1951 SelectionDAG &DAG) const {
1952 assert(getTargetMachine().getCodeModel() == CodeModel::Large);
1953 assert(getTargetMachine().getRelocationModel() == Reloc::Static);
1955 EVT PtrVT = getPointerTy();
1957 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
1958 const GlobalValue *GV = GN->getGlobal();
1960 SDValue GlobalAddr = DAG.getNode(
1961 AArch64ISD::WrapperLarge, dl, PtrVT,
1962 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G3),
1963 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G2_NC),
1964 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G1_NC),
1965 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G0_NC));
1967 if (GN->getOffset() != 0)
1968 return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalAddr,
1969 DAG.getConstant(GN->getOffset(), PtrVT));
1975 AArch64TargetLowering::LowerGlobalAddressELFSmall(SDValue Op,
1976 SelectionDAG &DAG) const {
1977 assert(getTargetMachine().getCodeModel() == CodeModel::Small);
1979 EVT PtrVT = getPointerTy();
1981 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
1982 const GlobalValue *GV = GN->getGlobal();
1983 unsigned Alignment = GV->getAlignment();
1984 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1985 if (GV->isWeakForLinker() && GV->isDeclaration() && RelocM == Reloc::Static) {
1986 // Weak undefined symbols can't use ADRP/ADD pair since they should evaluate
1987 // to zero when they remain undefined. In PIC mode the GOT can take care of
1988 // this, but in absolute mode we use a constant pool load.
1990 PoolAddr = DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
1991 DAG.getTargetConstantPool(GV, PtrVT, 0, 0,
1992 AArch64II::MO_NO_FLAG),
1993 DAG.getTargetConstantPool(GV, PtrVT, 0, 0,
1994 AArch64II::MO_LO12),
1995 DAG.getConstant(8, MVT::i32));
1996 SDValue GlobalAddr = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), PoolAddr,
1997 MachinePointerInfo::getConstantPool(),
1998 /*isVolatile=*/ false,
1999 /*isNonTemporal=*/ true,
2000 /*isInvariant=*/ true, 8);
2001 if (GN->getOffset() != 0)
2002 return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalAddr,
2003 DAG.getConstant(GN->getOffset(), PtrVT));
2008 if (Alignment == 0) {
2009 const PointerType *GVPtrTy = cast<PointerType>(GV->getType());
2010 if (GVPtrTy->getElementType()->isSized()) {
2012 = getDataLayout()->getABITypeAlignment(GVPtrTy->getElementType());
2014 // Be conservative if we can't guess, not that it really matters:
2015 // functions and labels aren't valid for loads, and the methods used to
2016 // actually calculate an address work with any alignment.
2021 unsigned char HiFixup, LoFixup;
2022 bool UseGOT = getSubtarget()->GVIsIndirectSymbol(GV, RelocM);
2025 HiFixup = AArch64II::MO_GOT;
2026 LoFixup = AArch64II::MO_GOT_LO12;
2029 HiFixup = AArch64II::MO_NO_FLAG;
2030 LoFixup = AArch64II::MO_LO12;
2033 // AArch64's small model demands the following sequence:
2034 // ADRP x0, somewhere
2035 // ADD x0, x0, #:lo12:somewhere ; (or LDR directly).
2036 SDValue GlobalRef = DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2037 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2039 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2041 DAG.getConstant(Alignment, MVT::i32));
2044 GlobalRef = DAG.getNode(AArch64ISD::GOTLoad, dl, PtrVT, DAG.getEntryNode(),
2048 if (GN->getOffset() != 0)
2049 return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalRef,
2050 DAG.getConstant(GN->getOffset(), PtrVT));
2056 AArch64TargetLowering::LowerGlobalAddressELF(SDValue Op,
2057 SelectionDAG &DAG) const {
2058 // TableGen doesn't have easy access to the CodeModel or RelocationModel, so
2059 // we make those distinctions here.
2061 switch (getTargetMachine().getCodeModel()) {
2062 case CodeModel::Small:
2063 return LowerGlobalAddressELFSmall(Op, DAG);
2064 case CodeModel::Large:
2065 return LowerGlobalAddressELFLarge(Op, DAG);
2067 llvm_unreachable("Only small and large code models supported now");
2071 SDValue AArch64TargetLowering::LowerTLSDescCall(SDValue SymAddr,
2074 SelectionDAG &DAG) const {
2075 EVT PtrVT = getPointerTy();
2077 // The function we need to call is simply the first entry in the GOT for this
2078 // descriptor, load it in preparation.
2079 SDValue Func, Chain;
2080 Func = DAG.getNode(AArch64ISD::GOTLoad, DL, PtrVT, DAG.getEntryNode(),
2083 // The function takes only one argument: the address of the descriptor itself
2086 Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::X0, DescAddr, Glue);
2087 Glue = Chain.getValue(1);
2089 // Finally, there's a special calling-convention which means that the lookup
2090 // must preserve all registers (except X0, obviously).
2091 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2092 const AArch64RegisterInfo *A64RI
2093 = static_cast<const AArch64RegisterInfo *>(TRI);
2094 const uint32_t *Mask = A64RI->getTLSDescCallPreservedMask();
2096 // We're now ready to populate the argument list, as with a normal call:
2097 std::vector<SDValue> Ops;
2098 Ops.push_back(Chain);
2099 Ops.push_back(Func);
2100 Ops.push_back(SymAddr);
2101 Ops.push_back(DAG.getRegister(AArch64::X0, PtrVT));
2102 Ops.push_back(DAG.getRegisterMask(Mask));
2103 Ops.push_back(Glue);
2105 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2106 Chain = DAG.getNode(AArch64ISD::TLSDESCCALL, DL, NodeTys, &Ops[0],
2108 Glue = Chain.getValue(1);
2110 // After the call, the offset from TPIDR_EL0 is in X0, copy it out and pass it
2111 // back to the generic handling code.
2112 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
2116 AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2117 SelectionDAG &DAG) const {
2118 assert(getSubtarget()->isTargetELF() &&
2119 "TLS not implemented for non-ELF targets");
2120 assert(getTargetMachine().getCodeModel() == CodeModel::Small
2121 && "TLS only supported in small memory model");
2122 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2124 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2127 EVT PtrVT = getPointerTy();
2129 const GlobalValue *GV = GA->getGlobal();
2131 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
2133 if (Model == TLSModel::InitialExec) {
2134 TPOff = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2135 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2136 AArch64II::MO_GOTTPREL),
2137 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2138 AArch64II::MO_GOTTPREL_LO12),
2139 DAG.getConstant(8, MVT::i32));
2140 TPOff = DAG.getNode(AArch64ISD::GOTLoad, DL, PtrVT, DAG.getEntryNode(),
2142 } else if (Model == TLSModel::LocalExec) {
2143 SDValue HiVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2144 AArch64II::MO_TPREL_G1);
2145 SDValue LoVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2146 AArch64II::MO_TPREL_G0_NC);
2148 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZxii, DL, PtrVT, HiVar,
2149 DAG.getTargetConstant(1, MVT::i32)), 0);
2150 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKxii, DL, PtrVT,
2152 DAG.getTargetConstant(0, MVT::i32)), 0);
2153 } else if (Model == TLSModel::GeneralDynamic) {
2154 // Accesses used in this sequence go via the TLS descriptor which lives in
2155 // the GOT. Prepare an address we can use to handle this.
2156 SDValue HiDesc = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2157 AArch64II::MO_TLSDESC);
2158 SDValue LoDesc = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2159 AArch64II::MO_TLSDESC_LO12);
2160 SDValue DescAddr = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2162 DAG.getConstant(8, MVT::i32));
2163 SDValue SymAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0);
2165 TPOff = LowerTLSDescCall(SymAddr, DescAddr, DL, DAG);
2166 } else if (Model == TLSModel::LocalDynamic) {
2167 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2168 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2169 // the beginning of the module's TLS region, followed by a DTPREL offset
2172 // These accesses will need deduplicating if there's more than one.
2173 AArch64MachineFunctionInfo* MFI = DAG.getMachineFunction()
2174 .getInfo<AArch64MachineFunctionInfo>();
2175 MFI->incNumLocalDynamicTLSAccesses();
2178 // Get the location of _TLS_MODULE_BASE_:
2179 SDValue HiDesc = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2180 AArch64II::MO_TLSDESC);
2181 SDValue LoDesc = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2182 AArch64II::MO_TLSDESC_LO12);
2183 SDValue DescAddr = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2185 DAG.getConstant(8, MVT::i32));
2186 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT);
2188 ThreadBase = LowerTLSDescCall(SymAddr, DescAddr, DL, DAG);
2190 // Get the variable's offset from _TLS_MODULE_BASE_
2191 SDValue HiVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2192 AArch64II::MO_DTPREL_G1);
2193 SDValue LoVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2194 AArch64II::MO_DTPREL_G0_NC);
2196 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZxii, DL, PtrVT, HiVar,
2197 DAG.getTargetConstant(0, MVT::i32)), 0);
2198 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKxii, DL, PtrVT,
2200 DAG.getTargetConstant(0, MVT::i32)), 0);
2202 llvm_unreachable("Unsupported TLS access model");
2205 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2209 AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG,
2210 bool IsSigned) const {
2211 if (Op.getValueType() != MVT::f128) {
2212 // Legal for everything except f128.
2218 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2220 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2222 return LowerF128ToCall(Op, DAG, LC);
2227 AArch64TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2228 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2230 EVT PtrVT = getPointerTy();
2232 // When compiling PIC, jump tables get put in the code section so a static
2233 // relocation-style is acceptable for both cases.
2234 switch (getTargetMachine().getCodeModel()) {
2235 case CodeModel::Small:
2236 return DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2237 DAG.getTargetJumpTable(JT->getIndex(), PtrVT),
2238 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2239 AArch64II::MO_LO12),
2240 DAG.getConstant(1, MVT::i32));
2241 case CodeModel::Large:
2243 AArch64ISD::WrapperLarge, dl, PtrVT,
2244 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G3),
2245 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G2_NC),
2246 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G1_NC),
2247 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G0_NC));
2249 llvm_unreachable("Only small and large code models supported now");
2253 // (SELECT_CC lhs, rhs, iftrue, iffalse, condcode)
2255 AArch64TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2257 SDValue LHS = Op.getOperand(0);
2258 SDValue RHS = Op.getOperand(1);
2259 SDValue IfTrue = Op.getOperand(2);
2260 SDValue IfFalse = Op.getOperand(3);
2261 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2263 if (LHS.getValueType() == MVT::f128) {
2264 // f128 comparisons are lowered to libcalls, but slot in nicely here
2266 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2268 // If softenSetCCOperands returned a scalar, we need to compare the result
2269 // against zero to select between true and false values.
2270 if (RHS.getNode() == 0) {
2271 RHS = DAG.getConstant(0, LHS.getValueType());
2276 if (LHS.getValueType().isInteger()) {
2279 // Integers are handled in a separate function because the combinations of
2280 // immediates and tests can get hairy and we may want to fiddle things.
2281 SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
2283 return DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2284 CmpOp, IfTrue, IfFalse, A64cc);
2287 // Note that some LLVM floating-point CondCodes can't be lowered to a single
2288 // conditional branch, hence FPCCToA64CC can set a second test, where either
2289 // passing is sufficient.
2290 A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
2291 CondCode = FPCCToA64CC(CC, Alternative);
2292 SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
2293 SDValue SetCC = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
2294 DAG.getCondCode(CC));
2295 SDValue A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl,
2297 SetCC, IfTrue, IfFalse, A64cc);
2299 if (Alternative != A64CC::Invalid) {
2300 A64cc = DAG.getConstant(Alternative, MVT::i32);
2301 A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2302 SetCC, IfTrue, A64SELECT_CC, A64cc);
2306 return A64SELECT_CC;
2309 // (SELECT testbit, iftrue, iffalse)
2311 AArch64TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2313 SDValue TheBit = Op.getOperand(0);
2314 SDValue IfTrue = Op.getOperand(1);
2315 SDValue IfFalse = Op.getOperand(2);
2317 // AArch64 BooleanContents is the default UndefinedBooleanContent, which means
2318 // that as the consumer we are responsible for ignoring rubbish in higher
2320 TheBit = DAG.getNode(ISD::AND, dl, MVT::i32, TheBit,
2321 DAG.getConstant(1, MVT::i32));
2322 SDValue A64CMP = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, TheBit,
2323 DAG.getConstant(0, TheBit.getValueType()),
2324 DAG.getCondCode(ISD::SETNE));
2326 return DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2327 A64CMP, IfTrue, IfFalse,
2328 DAG.getConstant(A64CC::NE, MVT::i32));
2331 static SDValue LowerVectorSETCC(SDValue Op, SelectionDAG &DAG) {
2333 SDValue LHS = Op.getOperand(0);
2334 SDValue RHS = Op.getOperand(1);
2335 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2336 EVT VT = Op.getValueType();
2337 bool Invert = false;
2341 if (LHS.getValueType().isInteger()) {
2343 // Attempt to use Vector Integer Compare Mask Test instruction.
2344 // TST = icmp ne (and (op0, op1), zero).
2345 if (CC == ISD::SETNE) {
2346 if (((LHS.getOpcode() == ISD::AND) &&
2347 ISD::isBuildVectorAllZeros(RHS.getNode())) ||
2348 ((RHS.getOpcode() == ISD::AND) &&
2349 ISD::isBuildVectorAllZeros(LHS.getNode()))) {
2351 SDValue AndOp = (LHS.getOpcode() == ISD::AND) ? LHS : RHS;
2352 SDValue NewLHS = DAG.getNode(ISD::BITCAST, DL, VT, AndOp.getOperand(0));
2353 SDValue NewRHS = DAG.getNode(ISD::BITCAST, DL, VT, AndOp.getOperand(1));
2354 return DAG.getNode(AArch64ISD::NEON_TST, DL, VT, NewLHS, NewRHS);
2358 // Attempt to use Vector Integer Compare Mask against Zero instr (Signed).
2359 // Note: Compare against Zero does not support unsigned predicates.
2360 if ((ISD::isBuildVectorAllZeros(RHS.getNode()) ||
2361 ISD::isBuildVectorAllZeros(LHS.getNode())) &&
2362 !isUnsignedIntSetCC(CC)) {
2364 // If LHS is the zero value, swap operands and CondCode.
2365 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
2366 CC = getSetCCSwappedOperands(CC);
2371 // Ensure valid CondCode for Compare Mask against Zero instruction:
2372 // EQ, GE, GT, LE, LT.
2373 if (ISD::SETNE == CC) {
2378 // Using constant type to differentiate integer and FP compares with zero.
2379 Op1 = DAG.getConstant(0, MVT::i32);
2380 Opcode = AArch64ISD::NEON_CMPZ;
2383 // Attempt to use Vector Integer Compare Mask instr (Signed/Unsigned).
2384 // Ensure valid CondCode for Compare Mask instr: EQ, GE, GT, UGE, UGT.
2388 llvm_unreachable("Illegal integer comparison.");
2404 CC = getSetCCSwappedOperands(CC);
2408 std::swap(LHS, RHS);
2410 Opcode = AArch64ISD::NEON_CMP;
2415 // Generate Compare Mask instr or Compare Mask against Zero instr.
2417 DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(CC));
2420 NeonCmp = DAG.getNOT(DL, NeonCmp, VT);
2425 // Now handle Floating Point cases.
2426 // Attempt to use Vector Floating Point Compare Mask against Zero instruction.
2427 if (ISD::isBuildVectorAllZeros(RHS.getNode()) ||
2428 ISD::isBuildVectorAllZeros(LHS.getNode())) {
2430 // If LHS is the zero value, swap operands and CondCode.
2431 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
2432 CC = getSetCCSwappedOperands(CC);
2437 // Using constant type to differentiate integer and FP compares with zero.
2438 Op1 = DAG.getConstantFP(0, MVT::f32);
2439 Opcode = AArch64ISD::NEON_CMPZ;
2441 // Attempt to use Vector Floating Point Compare Mask instruction.
2444 Opcode = AArch64ISD::NEON_CMP;
2448 // Some register compares have to be implemented with swapped CC and operands,
2449 // e.g.: OLT implemented as OGT with swapped operands.
2450 bool SwapIfRegArgs = false;
2452 // Ensure valid CondCode for FP Compare Mask against Zero instruction:
2453 // EQ, GE, GT, LE, LT.
2454 // And ensure valid CondCode for FP Compare Mask instruction: EQ, GE, GT.
2457 llvm_unreachable("Illegal FP comparison");
2460 Invert = true; // Fallthrough
2468 SwapIfRegArgs = true;
2477 SwapIfRegArgs = true;
2486 SwapIfRegArgs = true;
2495 SwapIfRegArgs = true;
2502 Invert = true; // Fallthrough
2504 // Expand this to (OGT |OLT).
2506 DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(ISD::SETGT));
2508 SwapIfRegArgs = true;
2511 Invert = true; // Fallthrough
2513 // Expand this to (OGE | OLT).
2515 DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(ISD::SETGE));
2517 SwapIfRegArgs = true;
2521 if (Opcode == AArch64ISD::NEON_CMP && SwapIfRegArgs) {
2522 CC = getSetCCSwappedOperands(CC);
2523 std::swap(Op0, Op1);
2526 // Generate FP Compare Mask instr or FP Compare Mask against Zero instr
2527 SDValue NeonCmp = DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(CC));
2529 if (NeonCmpAlt.getNode())
2530 NeonCmp = DAG.getNode(ISD::OR, DL, VT, NeonCmp, NeonCmpAlt);
2533 NeonCmp = DAG.getNOT(DL, NeonCmp, VT);
2538 // (SETCC lhs, rhs, condcode)
2540 AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2542 SDValue LHS = Op.getOperand(0);
2543 SDValue RHS = Op.getOperand(1);
2544 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2545 EVT VT = Op.getValueType();
2548 return LowerVectorSETCC(Op, DAG);
2550 if (LHS.getValueType() == MVT::f128) {
2551 // f128 comparisons will be lowered to libcalls giving a valid LHS and RHS
2552 // for the rest of the function (some i32 or i64 values).
2553 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2555 // If softenSetCCOperands returned a scalar, use it.
2556 if (RHS.getNode() == 0) {
2557 assert(LHS.getValueType() == Op.getValueType() &&
2558 "Unexpected setcc expansion!");
2563 if (LHS.getValueType().isInteger()) {
2566 // Integers are handled in a separate function because the combinations of
2567 // immediates and tests can get hairy and we may want to fiddle things.
2568 SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
2570 return DAG.getNode(AArch64ISD::SELECT_CC, dl, VT,
2571 CmpOp, DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2575 // Note that some LLVM floating-point CondCodes can't be lowered to a single
2576 // conditional branch, hence FPCCToA64CC can set a second test, where either
2577 // passing is sufficient.
2578 A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
2579 CondCode = FPCCToA64CC(CC, Alternative);
2580 SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
2581 SDValue CmpOp = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
2582 DAG.getCondCode(CC));
2583 SDValue A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT,
2584 CmpOp, DAG.getConstant(1, VT),
2585 DAG.getConstant(0, VT), A64cc);
2587 if (Alternative != A64CC::Invalid) {
2588 A64cc = DAG.getConstant(Alternative, MVT::i32);
2589 A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT, CmpOp,
2590 DAG.getConstant(1, VT), A64SELECT_CC, A64cc);
2593 return A64SELECT_CC;
2597 AArch64TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2598 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2599 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2601 // We have to make sure we copy the entire structure: 8+8+8+4+4 = 32 bytes
2602 // rather than just 8.
2603 return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op),
2604 Op.getOperand(1), Op.getOperand(2),
2605 DAG.getConstant(32, MVT::i32), 8, false, false,
2606 MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
2610 AArch64TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2611 // The layout of the va_list struct is specified in the AArch64 Procedure Call
2612 // Standard, section B.3.
2613 MachineFunction &MF = DAG.getMachineFunction();
2614 AArch64MachineFunctionInfo *FuncInfo
2615 = MF.getInfo<AArch64MachineFunctionInfo>();
2618 SDValue Chain = Op.getOperand(0);
2619 SDValue VAList = Op.getOperand(1);
2620 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2621 SmallVector<SDValue, 4> MemOps;
2623 // void *__stack at offset 0
2624 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVariadicStackIdx(),
2626 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
2627 MachinePointerInfo(SV), false, false, 0));
2629 // void *__gr_top at offset 8
2630 int GPRSize = FuncInfo->getVariadicGPRSize();
2632 SDValue GRTop, GRTopAddr;
2634 GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2635 DAG.getConstant(8, getPointerTy()));
2637 GRTop = DAG.getFrameIndex(FuncInfo->getVariadicGPRIdx(), getPointerTy());
2638 GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
2639 DAG.getConstant(GPRSize, getPointerTy()));
2641 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
2642 MachinePointerInfo(SV, 8),
2646 // void *__vr_top at offset 16
2647 int FPRSize = FuncInfo->getVariadicFPRSize();
2649 SDValue VRTop, VRTopAddr;
2650 VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2651 DAG.getConstant(16, getPointerTy()));
2653 VRTop = DAG.getFrameIndex(FuncInfo->getVariadicFPRIdx(), getPointerTy());
2654 VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
2655 DAG.getConstant(FPRSize, getPointerTy()));
2657 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
2658 MachinePointerInfo(SV, 16),
2662 // int __gr_offs at offset 24
2663 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2664 DAG.getConstant(24, getPointerTy()));
2665 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
2666 GROffsAddr, MachinePointerInfo(SV, 24),
2669 // int __vr_offs at offset 28
2670 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2671 DAG.getConstant(28, getPointerTy()));
2672 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
2673 VROffsAddr, MachinePointerInfo(SV, 28),
2676 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
2681 AArch64TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
2682 switch (Op.getOpcode()) {
2683 default: llvm_unreachable("Don't know how to custom lower this!");
2684 case ISD::FADD: return LowerF128ToCall(Op, DAG, RTLIB::ADD_F128);
2685 case ISD::FSUB: return LowerF128ToCall(Op, DAG, RTLIB::SUB_F128);
2686 case ISD::FMUL: return LowerF128ToCall(Op, DAG, RTLIB::MUL_F128);
2687 case ISD::FDIV: return LowerF128ToCall(Op, DAG, RTLIB::DIV_F128);
2688 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, true);
2689 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG, false);
2690 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG, true);
2691 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG, false);
2692 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
2693 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
2695 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
2696 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
2697 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
2698 case ISD::GlobalAddress: return LowerGlobalAddressELF(Op, DAG);
2699 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
2700 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
2701 case ISD::SELECT: return LowerSELECT(Op, DAG);
2702 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
2703 case ISD::SETCC: return LowerSETCC(Op, DAG);
2704 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
2705 case ISD::VASTART: return LowerVASTART(Op, DAG);
2706 case ISD::BUILD_VECTOR:
2707 return LowerBUILD_VECTOR(Op, DAG, getSubtarget());
2708 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
2714 /// Check if the specified splat value corresponds to a valid vector constant
2715 /// for a Neon instruction with a "modified immediate" operand (e.g., MOVI). If
2716 /// so, return the encoded 8-bit immediate and the OpCmode instruction fields
2718 static bool isNeonModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
2719 unsigned SplatBitSize, SelectionDAG &DAG,
2720 bool is128Bits, NeonModImmType type, EVT &VT,
2721 unsigned &Imm, unsigned &OpCmode) {
2722 switch (SplatBitSize) {
2724 llvm_unreachable("unexpected size for isNeonModifiedImm");
2726 if (type != Neon_Mov_Imm)
2728 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
2729 // Neon movi per byte: Op=0, Cmode=1110.
2732 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
2736 // Neon move inst per halfword
2737 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
2738 if ((SplatBits & ~0xff) == 0) {
2739 // Value = 0x00nn is 0x00nn LSL 0
2740 // movi: Op=0, Cmode=1000; mvni: Op=1, Cmode=1000
2741 // bic: Op=1, Cmode=1001; orr: Op=0, Cmode=1001
2747 if ((SplatBits & ~0xff00) == 0) {
2748 // Value = 0xnn00 is 0x00nn LSL 8
2749 // movi: Op=0, Cmode=1010; mvni: Op=1, Cmode=1010
2750 // bic: Op=1, Cmode=1011; orr: Op=0, Cmode=1011
2752 Imm = SplatBits >> 8;
2756 // can't handle any other
2761 // First the LSL variants (MSL is unusable by some interested instructions).
2763 // Neon move instr per word, shift zeros
2764 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
2765 if ((SplatBits & ~0xff) == 0) {
2766 // Value = 0x000000nn is 0x000000nn LSL 0
2767 // movi: Op=0, Cmode= 0000; mvni: Op=1, Cmode= 0000
2768 // bic: Op=1, Cmode= 0001; orr: Op=0, Cmode= 0001
2774 if ((SplatBits & ~0xff00) == 0) {
2775 // Value = 0x0000nn00 is 0x000000nn LSL 8
2776 // movi: Op=0, Cmode= 0010; mvni: Op=1, Cmode= 0010
2777 // bic: Op=1, Cmode= 0011; orr : Op=0, Cmode= 0011
2779 Imm = SplatBits >> 8;
2783 if ((SplatBits & ~0xff0000) == 0) {
2784 // Value = 0x00nn0000 is 0x000000nn LSL 16
2785 // movi: Op=0, Cmode= 0100; mvni: Op=1, Cmode= 0100
2786 // bic: Op=1, Cmode= 0101; orr: Op=0, Cmode= 0101
2788 Imm = SplatBits >> 16;
2792 if ((SplatBits & ~0xff000000) == 0) {
2793 // Value = 0xnn000000 is 0x000000nn LSL 24
2794 // movi: Op=0, Cmode= 0110; mvni: Op=1, Cmode= 0110
2795 // bic: Op=1, Cmode= 0111; orr: Op=0, Cmode= 0111
2797 Imm = SplatBits >> 24;
2802 // Now the MSL immediates.
2804 // Neon move instr per word, shift ones
2805 if ((SplatBits & ~0xffff) == 0 &&
2806 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
2807 // Value = 0x0000nnff is 0x000000nn MSL 8
2808 // movi: Op=0, Cmode= 1100; mvni: Op=1, Cmode= 1100
2810 Imm = SplatBits >> 8;
2814 if ((SplatBits & ~0xffffff) == 0 &&
2815 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
2816 // Value = 0x00nnffff is 0x000000nn MSL 16
2817 // movi: Op=1, Cmode= 1101; mvni: Op=1, Cmode= 1101
2819 Imm = SplatBits >> 16;
2823 // can't handle any other
2828 if (type != Neon_Mov_Imm)
2830 // Neon move instr bytemask, where each byte is either 0x00 or 0xff.
2831 // movi Op=1, Cmode=1110.
2833 uint64_t BitMask = 0xff;
2835 unsigned ImmMask = 1;
2837 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
2838 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
2841 } else if ((SplatBits & BitMask) != 0) {
2848 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
2856 static SDValue PerformANDCombine(SDNode *N,
2857 TargetLowering::DAGCombinerInfo &DCI) {
2859 SelectionDAG &DAG = DCI.DAG;
2861 EVT VT = N->getValueType(0);
2863 // We're looking for an SRA/SHL pair which form an SBFX.
2865 if (VT != MVT::i32 && VT != MVT::i64)
2868 if (!isa<ConstantSDNode>(N->getOperand(1)))
2871 uint64_t TruncMask = N->getConstantOperandVal(1);
2872 if (!isMask_64(TruncMask))
2875 uint64_t Width = CountPopulation_64(TruncMask);
2876 SDValue Shift = N->getOperand(0);
2878 if (Shift.getOpcode() != ISD::SRL)
2881 if (!isa<ConstantSDNode>(Shift->getOperand(1)))
2883 uint64_t LSB = Shift->getConstantOperandVal(1);
2885 if (LSB > VT.getSizeInBits() || Width > VT.getSizeInBits())
2888 return DAG.getNode(AArch64ISD::UBFX, DL, VT, Shift.getOperand(0),
2889 DAG.getConstant(LSB, MVT::i64),
2890 DAG.getConstant(LSB + Width - 1, MVT::i64));
2893 /// For a true bitfield insert, the bits getting into that contiguous mask
2894 /// should come from the low part of an existing value: they must be formed from
2895 /// a compatible SHL operation (unless they're already low). This function
2896 /// checks that condition and returns the least-significant bit that's
2897 /// intended. If the operation not a field preparation, -1 is returned.
2898 static int32_t getLSBForBFI(SelectionDAG &DAG, SDLoc DL, EVT VT,
2899 SDValue &MaskedVal, uint64_t Mask) {
2900 if (!isShiftedMask_64(Mask))
2903 // Now we need to alter MaskedVal so that it is an appropriate input for a BFI
2904 // instruction. BFI will do a left-shift by LSB before applying the mask we've
2905 // spotted, so in general we should pre-emptively "undo" that by making sure
2906 // the incoming bits have had a right-shift applied to them.
2908 // This right shift, however, will combine with existing left/right shifts. In
2909 // the simplest case of a completely straight bitfield operation, it will be
2910 // expected to completely cancel out with an existing SHL. More complicated
2911 // cases (e.g. bitfield to bitfield copy) may still need a real shift before
2914 uint64_t LSB = countTrailingZeros(Mask);
2915 int64_t ShiftRightRequired = LSB;
2916 if (MaskedVal.getOpcode() == ISD::SHL &&
2917 isa<ConstantSDNode>(MaskedVal.getOperand(1))) {
2918 ShiftRightRequired -= MaskedVal.getConstantOperandVal(1);
2919 MaskedVal = MaskedVal.getOperand(0);
2920 } else if (MaskedVal.getOpcode() == ISD::SRL &&
2921 isa<ConstantSDNode>(MaskedVal.getOperand(1))) {
2922 ShiftRightRequired += MaskedVal.getConstantOperandVal(1);
2923 MaskedVal = MaskedVal.getOperand(0);
2926 if (ShiftRightRequired > 0)
2927 MaskedVal = DAG.getNode(ISD::SRL, DL, VT, MaskedVal,
2928 DAG.getConstant(ShiftRightRequired, MVT::i64));
2929 else if (ShiftRightRequired < 0) {
2930 // We could actually end up with a residual left shift, for example with
2931 // "struc.bitfield = val << 1".
2932 MaskedVal = DAG.getNode(ISD::SHL, DL, VT, MaskedVal,
2933 DAG.getConstant(-ShiftRightRequired, MVT::i64));
2939 /// Searches from N for an existing AArch64ISD::BFI node, possibly surrounded by
2940 /// a mask and an extension. Returns true if a BFI was found and provides
2941 /// information on its surroundings.
2942 static bool findMaskedBFI(SDValue N, SDValue &BFI, uint64_t &Mask,
2945 if (N.getOpcode() == ISD::ZERO_EXTEND) {
2947 N = N.getOperand(0);
2950 if (N.getOpcode() == ISD::AND && isa<ConstantSDNode>(N.getOperand(1))) {
2951 Mask = N->getConstantOperandVal(1);
2952 N = N.getOperand(0);
2954 // Mask is the whole width.
2955 Mask = -1ULL >> (64 - N.getValueType().getSizeInBits());
2958 if (N.getOpcode() == AArch64ISD::BFI) {
2966 /// Try to combine a subtree (rooted at an OR) into a "masked BFI" node, which
2967 /// is roughly equivalent to (and (BFI ...), mask). This form is used because it
2968 /// can often be further combined with a larger mask. Ultimately, we want mask
2969 /// to be 2^32-1 or 2^64-1 so the AND can be skipped.
2970 static SDValue tryCombineToBFI(SDNode *N,
2971 TargetLowering::DAGCombinerInfo &DCI,
2972 const AArch64Subtarget *Subtarget) {
2973 SelectionDAG &DAG = DCI.DAG;
2975 EVT VT = N->getValueType(0);
2977 assert(N->getOpcode() == ISD::OR && "Unexpected root");
2979 // We need the LHS to be (and SOMETHING, MASK). Find out what that mask is or
2980 // abandon the effort.
2981 SDValue LHS = N->getOperand(0);
2982 if (LHS.getOpcode() != ISD::AND)
2986 if (isa<ConstantSDNode>(LHS.getOperand(1)))
2987 LHSMask = LHS->getConstantOperandVal(1);
2991 // We also need the RHS to be (and SOMETHING, MASK). Find out what that mask
2992 // is or abandon the effort.
2993 SDValue RHS = N->getOperand(1);
2994 if (RHS.getOpcode() != ISD::AND)
2998 if (isa<ConstantSDNode>(RHS.getOperand(1)))
2999 RHSMask = RHS->getConstantOperandVal(1);
3003 // Can't do anything if the masks are incompatible.
3004 if (LHSMask & RHSMask)
3007 // Now we need one of the masks to be a contiguous field. Without loss of
3008 // generality that should be the RHS one.
3009 SDValue Bitfield = LHS.getOperand(0);
3010 if (getLSBForBFI(DAG, DL, VT, Bitfield, LHSMask) != -1) {
3011 // We know that LHS is a candidate new value, and RHS isn't already a better
3013 std::swap(LHS, RHS);
3014 std::swap(LHSMask, RHSMask);
3017 // We've done our best to put the right operands in the right places, all we
3018 // can do now is check whether a BFI exists.
3019 Bitfield = RHS.getOperand(0);
3020 int32_t LSB = getLSBForBFI(DAG, DL, VT, Bitfield, RHSMask);
3024 uint32_t Width = CountPopulation_64(RHSMask);
3025 assert(Width && "Expected non-zero bitfield width");
3027 SDValue BFI = DAG.getNode(AArch64ISD::BFI, DL, VT,
3028 LHS.getOperand(0), Bitfield,
3029 DAG.getConstant(LSB, MVT::i64),
3030 DAG.getConstant(Width, MVT::i64));
3033 if ((LHSMask | RHSMask) == (-1ULL >> (64 - VT.getSizeInBits())))
3036 return DAG.getNode(ISD::AND, DL, VT, BFI,
3037 DAG.getConstant(LHSMask | RHSMask, VT));
3040 /// Search for the bitwise combining (with careful masks) of a MaskedBFI and its
3041 /// original input. This is surprisingly common because SROA splits things up
3042 /// into i8 chunks, so the originally detected MaskedBFI may actually only act
3043 /// on the low (say) byte of a word. This is then orred into the rest of the
3044 /// word afterwards.
3046 /// Basic input: (or (and OLDFIELD, MASK1), (MaskedBFI MASK2, OLDFIELD, ...)).
3048 /// If MASK1 and MASK2 are compatible, we can fold the whole thing into the
3049 /// MaskedBFI. We can also deal with a certain amount of extend/truncate being
3051 static SDValue tryCombineToLargerBFI(SDNode *N,
3052 TargetLowering::DAGCombinerInfo &DCI,
3053 const AArch64Subtarget *Subtarget) {
3054 SelectionDAG &DAG = DCI.DAG;
3056 EVT VT = N->getValueType(0);
3058 // First job is to hunt for a MaskedBFI on either the left or right. Swap
3059 // operands if it's actually on the right.
3061 SDValue PossExtraMask;
3062 uint64_t ExistingMask = 0;
3063 bool Extended = false;
3064 if (findMaskedBFI(N->getOperand(0), BFI, ExistingMask, Extended))
3065 PossExtraMask = N->getOperand(1);
3066 else if (findMaskedBFI(N->getOperand(1), BFI, ExistingMask, Extended))
3067 PossExtraMask = N->getOperand(0);
3071 // We can only combine a BFI with another compatible mask.
3072 if (PossExtraMask.getOpcode() != ISD::AND ||
3073 !isa<ConstantSDNode>(PossExtraMask.getOperand(1)))
3076 uint64_t ExtraMask = PossExtraMask->getConstantOperandVal(1);
3078 // Masks must be compatible.
3079 if (ExtraMask & ExistingMask)
3082 SDValue OldBFIVal = BFI.getOperand(0);
3083 SDValue NewBFIVal = BFI.getOperand(1);
3085 // We skipped a ZERO_EXTEND above, so the input to the MaskedBFIs should be
3086 // 32-bit and we'll be forming a 64-bit MaskedBFI. The MaskedBFI arguments
3087 // need to be made compatible.
3088 assert(VT == MVT::i64 && BFI.getValueType() == MVT::i32
3089 && "Invalid types for BFI");
3090 OldBFIVal = DAG.getNode(ISD::ANY_EXTEND, DL, VT, OldBFIVal);
3091 NewBFIVal = DAG.getNode(ISD::ANY_EXTEND, DL, VT, NewBFIVal);
3094 // We need the MaskedBFI to be combined with a mask of the *same* value.
3095 if (PossExtraMask.getOperand(0) != OldBFIVal)
3098 BFI = DAG.getNode(AArch64ISD::BFI, DL, VT,
3099 OldBFIVal, NewBFIVal,
3100 BFI.getOperand(2), BFI.getOperand(3));
3102 // If the masking is trivial, we don't need to create it.
3103 if ((ExtraMask | ExistingMask) == (-1ULL >> (64 - VT.getSizeInBits())))
3106 return DAG.getNode(ISD::AND, DL, VT, BFI,
3107 DAG.getConstant(ExtraMask | ExistingMask, VT));
3110 /// An EXTR instruction is made up of two shifts, ORed together. This helper
3111 /// searches for and classifies those shifts.
3112 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
3114 if (N.getOpcode() == ISD::SHL)
3116 else if (N.getOpcode() == ISD::SRL)
3121 if (!isa<ConstantSDNode>(N.getOperand(1)))
3124 ShiftAmount = N->getConstantOperandVal(1);
3125 Src = N->getOperand(0);
3129 /// EXTR instruction extracts a contiguous chunk of bits from two existing
3130 /// registers viewed as a high/low pair. This function looks for the pattern:
3131 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
3132 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
3134 static SDValue tryCombineToEXTR(SDNode *N,
3135 TargetLowering::DAGCombinerInfo &DCI) {
3136 SelectionDAG &DAG = DCI.DAG;
3138 EVT VT = N->getValueType(0);
3140 assert(N->getOpcode() == ISD::OR && "Unexpected root");
3142 if (VT != MVT::i32 && VT != MVT::i64)
3146 uint32_t ShiftLHS = 0;
3148 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
3152 uint32_t ShiftRHS = 0;
3154 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
3157 // If they're both trying to come from the high part of the register, they're
3158 // not really an EXTR.
3159 if (LHSFromHi == RHSFromHi)
3162 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
3166 std::swap(LHS, RHS);
3167 std::swap(ShiftLHS, ShiftRHS);
3170 return DAG.getNode(AArch64ISD::EXTR, DL, VT,
3172 DAG.getConstant(ShiftRHS, MVT::i64));
3175 /// Target-specific dag combine xforms for ISD::OR
3176 static SDValue PerformORCombine(SDNode *N,
3177 TargetLowering::DAGCombinerInfo &DCI,
3178 const AArch64Subtarget *Subtarget) {
3180 SelectionDAG &DAG = DCI.DAG;
3182 EVT VT = N->getValueType(0);
3184 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
3187 // Attempt to recognise bitfield-insert operations.
3188 SDValue Res = tryCombineToBFI(N, DCI, Subtarget);
3192 // Attempt to combine an existing MaskedBFI operation into one with a larger
3194 Res = tryCombineToLargerBFI(N, DCI, Subtarget);
3198 Res = tryCombineToEXTR(N, DCI);
3202 if (!Subtarget->hasNEON())
3205 // Attempt to use vector immediate-form BSL
3206 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
3208 SDValue N0 = N->getOperand(0);
3209 if (N0.getOpcode() != ISD::AND)
3212 SDValue N1 = N->getOperand(1);
3213 if (N1.getOpcode() != ISD::AND)
3216 if (VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
3218 unsigned SplatBitSize;
3220 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
3222 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
3225 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
3227 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
3229 !HasAnyUndefs && SplatBits0 == ~SplatBits1) {
3230 // Canonicalize the vector type to make instruction selection simpler.
3231 EVT CanonicalVT = VT.is128BitVector() ? MVT::v16i8 : MVT::v8i8;
3232 SDValue Result = DAG.getNode(AArch64ISD::NEON_BSL, DL, CanonicalVT,
3233 N0->getOperand(1), N0->getOperand(0),
3235 return DAG.getNode(ISD::BITCAST, DL, VT, Result);
3243 /// Target-specific dag combine xforms for ISD::SRA
3244 static SDValue PerformSRACombine(SDNode *N,
3245 TargetLowering::DAGCombinerInfo &DCI) {
3247 SelectionDAG &DAG = DCI.DAG;
3249 EVT VT = N->getValueType(0);
3251 // We're looking for an SRA/SHL pair which form an SBFX.
3253 if (VT != MVT::i32 && VT != MVT::i64)
3256 if (!isa<ConstantSDNode>(N->getOperand(1)))
3259 uint64_t ExtraSignBits = N->getConstantOperandVal(1);
3260 SDValue Shift = N->getOperand(0);
3262 if (Shift.getOpcode() != ISD::SHL)
3265 if (!isa<ConstantSDNode>(Shift->getOperand(1)))
3268 uint64_t BitsOnLeft = Shift->getConstantOperandVal(1);
3269 uint64_t Width = VT.getSizeInBits() - ExtraSignBits;
3270 uint64_t LSB = VT.getSizeInBits() - Width - BitsOnLeft;
3272 if (LSB > VT.getSizeInBits() || Width > VT.getSizeInBits())
3275 return DAG.getNode(AArch64ISD::SBFX, DL, VT, Shift.getOperand(0),
3276 DAG.getConstant(LSB, MVT::i64),
3277 DAG.getConstant(LSB + Width - 1, MVT::i64));
3280 /// Check if this is a valid build_vector for the immediate operand of
3281 /// a vector shift operation, where all the elements of the build_vector
3282 /// must have the same constant integer value.
3283 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
3284 // Ignore bit_converts.
3285 while (Op.getOpcode() == ISD::BITCAST)
3286 Op = Op.getOperand(0);
3287 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
3288 APInt SplatBits, SplatUndef;
3289 unsigned SplatBitSize;
3291 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
3292 HasAnyUndefs, ElementBits) ||
3293 SplatBitSize > ElementBits)
3295 Cnt = SplatBits.getSExtValue();
3299 /// Check if this is a valid build_vector for the immediate operand of
3300 /// a vector shift left operation. That value must be in the range:
3301 /// 0 <= Value < ElementBits
3302 static bool isVShiftLImm(SDValue Op, EVT VT, int64_t &Cnt) {
3303 assert(VT.isVector() && "vector shift count is not a vector type");
3304 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3305 if (!getVShiftImm(Op, ElementBits, Cnt))
3307 return (Cnt >= 0 && Cnt < ElementBits);
3310 /// Check if this is a valid build_vector for the immediate operand of a
3311 /// vector shift right operation. The value must be in the range:
3312 /// 1 <= Value <= ElementBits
3313 static bool isVShiftRImm(SDValue Op, EVT VT, int64_t &Cnt) {
3314 assert(VT.isVector() && "vector shift count is not a vector type");
3315 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3316 if (!getVShiftImm(Op, ElementBits, Cnt))
3318 return (Cnt >= 1 && Cnt <= ElementBits);
3321 /// Checks for immediate versions of vector shifts and lowers them.
3322 static SDValue PerformShiftCombine(SDNode *N,
3323 TargetLowering::DAGCombinerInfo &DCI,
3324 const AArch64Subtarget *ST) {
3325 SelectionDAG &DAG = DCI.DAG;
3326 EVT VT = N->getValueType(0);
3327 if (N->getOpcode() == ISD::SRA && (VT == MVT::i32 || VT == MVT::i64))
3328 return PerformSRACombine(N, DCI);
3330 // Nothing to be done for scalar shifts.
3331 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3332 if (!VT.isVector() || !TLI.isTypeLegal(VT))
3335 assert(ST->hasNEON() && "unexpected vector shift");
3338 switch (N->getOpcode()) {
3340 llvm_unreachable("unexpected shift opcode");
3343 if (isVShiftLImm(N->getOperand(1), VT, Cnt)) {
3345 DAG.getNode(AArch64ISD::NEON_DUPIMM, SDLoc(N->getOperand(1)), VT,
3346 DAG.getConstant(Cnt, MVT::i32));
3347 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0), RHS);
3353 if (isVShiftRImm(N->getOperand(1), VT, Cnt)) {
3355 DAG.getNode(AArch64ISD::NEON_DUPIMM, SDLoc(N->getOperand(1)), VT,
3356 DAG.getConstant(Cnt, MVT::i32));
3357 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N->getOperand(0), RHS);
3365 /// ARM-specific DAG combining for intrinsics.
3366 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
3367 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3371 // Don't do anything for most intrinsics.
3374 case Intrinsic::arm_neon_vqshifts:
3375 case Intrinsic::arm_neon_vqshiftu:
3376 EVT VT = N->getOperand(1).getValueType();
3378 if (!isVShiftLImm(N->getOperand(2), VT, Cnt))
3380 unsigned VShiftOpc = (IntNo == Intrinsic::arm_neon_vqshifts)
3381 ? AArch64ISD::NEON_QSHLs
3382 : AArch64ISD::NEON_QSHLu;
3383 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
3384 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
3391 AArch64TargetLowering::PerformDAGCombine(SDNode *N,
3392 DAGCombinerInfo &DCI) const {
3393 switch (N->getOpcode()) {
3395 case ISD::AND: return PerformANDCombine(N, DCI);
3396 case ISD::OR: return PerformORCombine(N, DCI, getSubtarget());
3400 return PerformShiftCombine(N, DCI, getSubtarget());
3401 case ISD::INTRINSIC_WO_CHAIN:
3402 return PerformIntrinsicCombine(N, DCI.DAG);
3408 AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3409 VT = VT.getScalarType();
3414 switch (VT.getSimpleVT().SimpleTy) {
3428 // If this is a case we can't handle, return null and let the default
3429 // expansion code take care of it.
3431 AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
3432 const AArch64Subtarget *ST) const {
3434 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
3436 EVT VT = Op.getValueType();
3438 APInt SplatBits, SplatUndef;
3439 unsigned SplatBitSize;
3442 // Note we favor lowering MOVI over MVNI.
3443 // This has implications on the definition of patterns in TableGen to select
3444 // BIC immediate instructions but not ORR immediate instructions.
3445 // If this lowering order is changed, TableGen patterns for BIC immediate and
3446 // ORR immediate instructions have to be updated.
3447 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
3448 if (SplatBitSize <= 64) {
3449 // First attempt to use vector immediate-form MOVI
3452 unsigned OpCmode = 0;
3454 if (isNeonModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
3455 SplatBitSize, DAG, VT.is128BitVector(),
3456 Neon_Mov_Imm, NeonMovVT, Imm, OpCmode)) {
3457 SDValue ImmVal = DAG.getTargetConstant(Imm, MVT::i32);
3458 SDValue OpCmodeVal = DAG.getConstant(OpCmode, MVT::i32);
3460 if (ImmVal.getNode() && OpCmodeVal.getNode()) {
3461 SDValue NeonMov = DAG.getNode(AArch64ISD::NEON_MOVIMM, DL, NeonMovVT,
3462 ImmVal, OpCmodeVal);
3463 return DAG.getNode(ISD::BITCAST, DL, VT, NeonMov);
3467 // Then attempt to use vector immediate-form MVNI
3468 uint64_t NegatedImm = (~SplatBits).getZExtValue();
3469 if (isNeonModifiedImm(NegatedImm, SplatUndef.getZExtValue(), SplatBitSize,
3470 DAG, VT.is128BitVector(), Neon_Mvn_Imm, NeonMovVT,
3472 SDValue ImmVal = DAG.getTargetConstant(Imm, MVT::i32);
3473 SDValue OpCmodeVal = DAG.getConstant(OpCmode, MVT::i32);
3474 if (ImmVal.getNode() && OpCmodeVal.getNode()) {
3475 SDValue NeonMov = DAG.getNode(AArch64ISD::NEON_MVNIMM, DL, NeonMovVT,
3476 ImmVal, OpCmodeVal);
3477 return DAG.getNode(ISD::BITCAST, DL, VT, NeonMov);
3481 // Attempt to use vector immediate-form FMOV
3482 if (((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) ||
3483 (VT == MVT::v2f64 && SplatBitSize == 64)) {
3485 SplatBitSize == 32 ? APFloat::IEEEsingle : APFloat::IEEEdouble,
3488 if (A64Imms::isFPImm(RealVal, ImmVal)) {
3489 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
3490 return DAG.getNode(AArch64ISD::NEON_FMOVIMM, DL, VT, Val);
3499 AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
3500 SelectionDAG &DAG) const {
3501 SDValue V1 = Op.getOperand(0);
3503 EVT VT = Op.getValueType();
3504 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
3506 // Convert shuffles that are directly supported on NEON to target-specific
3507 // DAG nodes, instead of keeping them as shuffles and matching them again
3508 // during code selection. This is more efficient and avoids the possibility
3509 // of inconsistencies between legalization and selection.
3510 ArrayRef<int> ShuffleMask = SVN->getMask();
3512 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3513 if (EltSize <= 64) {
3514 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
3515 int Lane = SVN->getSplatIndex();
3516 // If this is undef splat, generate it via "just" vdup, if possible.
3517 if (Lane == -1) Lane = 0;
3519 return DAG.getNode(AArch64ISD::NEON_VDUPLANE, dl, VT, V1,
3520 DAG.getConstant(Lane, MVT::i64));
3527 AArch64TargetLowering::ConstraintType
3528 AArch64TargetLowering::getConstraintType(const std::string &Constraint) const {
3529 if (Constraint.size() == 1) {
3530 switch (Constraint[0]) {
3532 case 'w': // An FP/SIMD vector register
3533 return C_RegisterClass;
3534 case 'I': // Constant that can be used with an ADD instruction
3535 case 'J': // Constant that can be used with a SUB instruction
3536 case 'K': // Constant that can be used with a 32-bit logical instruction
3537 case 'L': // Constant that can be used with a 64-bit logical instruction
3538 case 'M': // Constant that can be used as a 32-bit MOV immediate
3539 case 'N': // Constant that can be used as a 64-bit MOV immediate
3540 case 'Y': // Floating point constant zero
3541 case 'Z': // Integer constant zero
3543 case 'Q': // A memory reference with base register and no offset
3545 case 'S': // A symbolic address
3550 // FIXME: Ump, Utf, Usa, Ush
3551 // Ump: A memory address suitable for ldp/stp in SI, DI, SF and DF modes,
3552 // whatever they may be
3553 // Utf: A memory address suitable for ldp/stp in TF mode, whatever it may be
3554 // Usa: An absolute symbolic address
3555 // Ush: The high part (bits 32:12) of a pc-relative symbolic address
3556 assert(Constraint != "Ump" && Constraint != "Utf" && Constraint != "Usa"
3557 && Constraint != "Ush" && "Unimplemented constraints");
3559 return TargetLowering::getConstraintType(Constraint);
3562 TargetLowering::ConstraintWeight
3563 AArch64TargetLowering::getSingleConstraintMatchWeight(AsmOperandInfo &Info,
3564 const char *Constraint) const {
3566 llvm_unreachable("Constraint weight unimplemented");
3570 AArch64TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3571 std::string &Constraint,
3572 std::vector<SDValue> &Ops,
3573 SelectionDAG &DAG) const {
3574 SDValue Result(0, 0);
3576 // Only length 1 constraints are C_Other.
3577 if (Constraint.size() != 1) return;
3579 // Only C_Other constraints get lowered like this. That means constants for us
3580 // so return early if there's no hope the constraint can be lowered.
3582 switch(Constraint[0]) {
3584 case 'I': case 'J': case 'K': case 'L':
3585 case 'M': case 'N': case 'Z': {
3586 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3590 uint64_t CVal = C->getZExtValue();
3593 switch (Constraint[0]) {
3595 // FIXME: 'M' and 'N' are MOV pseudo-insts -- unsupported in assembly. 'J'
3596 // is a peculiarly useless SUB constraint.
3597 llvm_unreachable("Unimplemented C_Other constraint");
3603 if (A64Imms::isLogicalImm(32, CVal, Bits))
3607 if (A64Imms::isLogicalImm(64, CVal, Bits))
3616 Result = DAG.getTargetConstant(CVal, Op.getValueType());
3620 // An absolute symbolic address or label reference.
3621 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
3622 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
3623 GA->getValueType(0));
3624 } else if (const BlockAddressSDNode *BA
3625 = dyn_cast<BlockAddressSDNode>(Op)) {
3626 Result = DAG.getTargetBlockAddress(BA->getBlockAddress(),
3627 BA->getValueType(0));
3628 } else if (const ExternalSymbolSDNode *ES
3629 = dyn_cast<ExternalSymbolSDNode>(Op)) {
3630 Result = DAG.getTargetExternalSymbol(ES->getSymbol(),
3631 ES->getValueType(0));
3637 if (const ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
3638 if (CFP->isExactlyValue(0.0)) {
3639 Result = DAG.getTargetConstantFP(0.0, CFP->getValueType(0));
3646 if (Result.getNode()) {
3647 Ops.push_back(Result);
3651 // It's an unknown constraint for us. Let generic code have a go.
3652 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3655 std::pair<unsigned, const TargetRegisterClass*>
3656 AArch64TargetLowering::getRegForInlineAsmConstraint(
3657 const std::string &Constraint,
3659 if (Constraint.size() == 1) {
3660 switch (Constraint[0]) {
3662 if (VT.getSizeInBits() <= 32)
3663 return std::make_pair(0U, &AArch64::GPR32RegClass);
3664 else if (VT == MVT::i64)
3665 return std::make_pair(0U, &AArch64::GPR64RegClass);
3669 return std::make_pair(0U, &AArch64::FPR16RegClass);
3670 else if (VT == MVT::f32)
3671 return std::make_pair(0U, &AArch64::FPR32RegClass);
3672 else if (VT.getSizeInBits() == 64)
3673 return std::make_pair(0U, &AArch64::FPR64RegClass);
3674 else if (VT.getSizeInBits() == 128)
3675 return std::make_pair(0U, &AArch64::FPR128RegClass);
3680 // Use the default implementation in TargetLowering to convert the register
3681 // constraint into a member of a register class.
3682 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3685 /// Represent NEON load and store intrinsics as MemIntrinsicNodes.
3686 /// The associated MachineMemOperands record the alignment specified
3687 /// in the intrinsic calls.
3688 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
3690 unsigned Intrinsic) const {
3691 switch (Intrinsic) {
3692 case Intrinsic::arm_neon_vld1:
3693 case Intrinsic::arm_neon_vld2:
3694 case Intrinsic::arm_neon_vld3:
3695 case Intrinsic::arm_neon_vld4: {
3696 Info.opc = ISD::INTRINSIC_W_CHAIN;
3697 // Conservatively set memVT to the entire set of vectors loaded.
3698 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
3699 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
3700 Info.ptrVal = I.getArgOperand(0);
3702 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
3703 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
3704 Info.vol = false; // volatile loads with NEON intrinsics not supported
3705 Info.readMem = true;
3706 Info.writeMem = false;
3709 case Intrinsic::arm_neon_vst1:
3710 case Intrinsic::arm_neon_vst2:
3711 case Intrinsic::arm_neon_vst3:
3712 case Intrinsic::arm_neon_vst4: {
3713 Info.opc = ISD::INTRINSIC_VOID;
3714 // Conservatively set memVT to the entire set of vectors stored.
3715 unsigned NumElts = 0;
3716 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
3717 Type *ArgTy = I.getArgOperand(ArgI)->getType();
3718 if (!ArgTy->isVectorTy())
3720 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
3722 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
3723 Info.ptrVal = I.getArgOperand(0);
3725 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
3726 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
3727 Info.vol = false; // volatile stores with NEON intrinsics not supported
3728 Info.readMem = false;
3729 Info.writeMem = true;