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::CONCAT_VECTORS, MVT::v2i64, Legal);
302 setOperationAction(ISD::SETCC, MVT::v8i8, Custom);
303 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
304 setOperationAction(ISD::SETCC, MVT::v4i16, Custom);
305 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
306 setOperationAction(ISD::SETCC, MVT::v2i32, Custom);
307 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
308 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
309 setOperationAction(ISD::SETCC, MVT::v2f32, Custom);
310 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
311 setOperationAction(ISD::SETCC, MVT::v2f64, Custom);
315 EVT AArch64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
316 // It's reasonably important that this value matches the "natural" legal
317 // promotion from i1 for scalar types. Otherwise LegalizeTypes can get itself
318 // in a twist (e.g. inserting an any_extend which then becomes i64 -> i64).
319 if (!VT.isVector()) return MVT::i32;
320 return VT.changeVectorElementTypeToInteger();
323 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
326 static const unsigned LoadBares[] = {AArch64::LDXR_byte, AArch64::LDXR_hword,
327 AArch64::LDXR_word, AArch64::LDXR_dword};
328 static const unsigned LoadAcqs[] = {AArch64::LDAXR_byte, AArch64::LDAXR_hword,
329 AArch64::LDAXR_word, AArch64::LDAXR_dword};
330 static const unsigned StoreBares[] = {AArch64::STXR_byte, AArch64::STXR_hword,
331 AArch64::STXR_word, AArch64::STXR_dword};
332 static const unsigned StoreRels[] = {AArch64::STLXR_byte,AArch64::STLXR_hword,
333 AArch64::STLXR_word, AArch64::STLXR_dword};
335 const unsigned *LoadOps, *StoreOps;
336 if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
341 if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
342 StoreOps = StoreRels;
344 StoreOps = StoreBares;
346 assert(isPowerOf2_32(Size) && Size <= 8 &&
347 "unsupported size for atomic binary op!");
349 LdrOpc = LoadOps[Log2_32(Size)];
350 StrOpc = StoreOps[Log2_32(Size)];
354 AArch64TargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
356 unsigned BinOpcode) const {
357 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
358 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
360 const BasicBlock *LLVM_BB = BB->getBasicBlock();
361 MachineFunction *MF = BB->getParent();
362 MachineFunction::iterator It = BB;
365 unsigned dest = MI->getOperand(0).getReg();
366 unsigned ptr = MI->getOperand(1).getReg();
367 unsigned incr = MI->getOperand(2).getReg();
368 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
369 DebugLoc dl = MI->getDebugLoc();
371 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
373 unsigned ldrOpc, strOpc;
374 getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
376 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
377 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
378 MF->insert(It, loopMBB);
379 MF->insert(It, exitMBB);
381 // Transfer the remainder of BB and its successor edges to exitMBB.
382 exitMBB->splice(exitMBB->begin(), BB,
383 llvm::next(MachineBasicBlock::iterator(MI)),
385 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
387 const TargetRegisterClass *TRC
388 = Size == 8 ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
389 unsigned scratch = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
393 // fallthrough --> loopMBB
394 BB->addSuccessor(loopMBB);
398 // <binop> scratch, dest, incr
399 // stxr stxr_status, scratch, ptr
400 // cbnz stxr_status, loopMBB
401 // fallthrough --> exitMBB
403 BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
405 // All arithmetic operations we'll be creating are designed to take an extra
406 // shift or extend operand, which we can conveniently set to zero.
408 // Operand order needs to go the other way for NAND.
409 if (BinOpcode == AArch64::BICwww_lsl || BinOpcode == AArch64::BICxxx_lsl)
410 BuildMI(BB, dl, TII->get(BinOpcode), scratch)
411 .addReg(incr).addReg(dest).addImm(0);
413 BuildMI(BB, dl, TII->get(BinOpcode), scratch)
414 .addReg(dest).addReg(incr).addImm(0);
417 // From the stxr, the register is GPR32; from the cmp it's GPR32wsp
418 unsigned stxr_status = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
419 MRI.constrainRegClass(stxr_status, &AArch64::GPR32wspRegClass);
421 BuildMI(BB, dl, TII->get(strOpc), stxr_status).addReg(scratch).addReg(ptr);
422 BuildMI(BB, dl, TII->get(AArch64::CBNZw))
423 .addReg(stxr_status).addMBB(loopMBB);
425 BB->addSuccessor(loopMBB);
426 BB->addSuccessor(exitMBB);
432 MI->eraseFromParent(); // The instruction is gone now.
438 AArch64TargetLowering::emitAtomicBinaryMinMax(MachineInstr *MI,
439 MachineBasicBlock *BB,
442 A64CC::CondCodes Cond) const {
443 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
445 const BasicBlock *LLVM_BB = BB->getBasicBlock();
446 MachineFunction *MF = BB->getParent();
447 MachineFunction::iterator It = BB;
450 unsigned dest = MI->getOperand(0).getReg();
451 unsigned ptr = MI->getOperand(1).getReg();
452 unsigned incr = MI->getOperand(2).getReg();
453 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
455 unsigned oldval = dest;
456 DebugLoc dl = MI->getDebugLoc();
458 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
459 const TargetRegisterClass *TRC, *TRCsp;
461 TRC = &AArch64::GPR64RegClass;
462 TRCsp = &AArch64::GPR64xspRegClass;
464 TRC = &AArch64::GPR32RegClass;
465 TRCsp = &AArch64::GPR32wspRegClass;
468 unsigned ldrOpc, strOpc;
469 getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
471 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
472 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
473 MF->insert(It, loopMBB);
474 MF->insert(It, exitMBB);
476 // Transfer the remainder of BB and its successor edges to exitMBB.
477 exitMBB->splice(exitMBB->begin(), BB,
478 llvm::next(MachineBasicBlock::iterator(MI)),
480 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
482 unsigned scratch = MRI.createVirtualRegister(TRC);
483 MRI.constrainRegClass(scratch, TRCsp);
487 // fallthrough --> loopMBB
488 BB->addSuccessor(loopMBB);
492 // cmp incr, dest (, sign extend if necessary)
493 // csel scratch, dest, incr, cond
494 // stxr stxr_status, scratch, ptr
495 // cbnz stxr_status, loopMBB
496 // fallthrough --> exitMBB
498 BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
500 // Build compare and cmov instructions.
501 MRI.constrainRegClass(incr, TRCsp);
502 BuildMI(BB, dl, TII->get(CmpOp))
503 .addReg(incr).addReg(oldval).addImm(0);
505 BuildMI(BB, dl, TII->get(Size == 8 ? AArch64::CSELxxxc : AArch64::CSELwwwc),
507 .addReg(oldval).addReg(incr).addImm(Cond);
509 unsigned stxr_status = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
510 MRI.constrainRegClass(stxr_status, &AArch64::GPR32wspRegClass);
512 BuildMI(BB, dl, TII->get(strOpc), stxr_status)
513 .addReg(scratch).addReg(ptr);
514 BuildMI(BB, dl, TII->get(AArch64::CBNZw))
515 .addReg(stxr_status).addMBB(loopMBB);
517 BB->addSuccessor(loopMBB);
518 BB->addSuccessor(exitMBB);
524 MI->eraseFromParent(); // The instruction is gone now.
530 AArch64TargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
531 MachineBasicBlock *BB,
532 unsigned Size) const {
533 unsigned dest = MI->getOperand(0).getReg();
534 unsigned ptr = MI->getOperand(1).getReg();
535 unsigned oldval = MI->getOperand(2).getReg();
536 unsigned newval = MI->getOperand(3).getReg();
537 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
538 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
539 DebugLoc dl = MI->getDebugLoc();
541 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
542 const TargetRegisterClass *TRCsp;
543 TRCsp = Size == 8 ? &AArch64::GPR64xspRegClass : &AArch64::GPR32wspRegClass;
545 unsigned ldrOpc, strOpc;
546 getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
548 MachineFunction *MF = BB->getParent();
549 const BasicBlock *LLVM_BB = BB->getBasicBlock();
550 MachineFunction::iterator It = BB;
551 ++It; // insert the new blocks after the current block
553 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
554 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
555 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
556 MF->insert(It, loop1MBB);
557 MF->insert(It, loop2MBB);
558 MF->insert(It, exitMBB);
560 // Transfer the remainder of BB and its successor edges to exitMBB.
561 exitMBB->splice(exitMBB->begin(), BB,
562 llvm::next(MachineBasicBlock::iterator(MI)),
564 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
568 // fallthrough --> loop1MBB
569 BB->addSuccessor(loop1MBB);
576 BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
578 unsigned CmpOp = Size == 8 ? AArch64::CMPxx_lsl : AArch64::CMPww_lsl;
579 MRI.constrainRegClass(dest, TRCsp);
580 BuildMI(BB, dl, TII->get(CmpOp))
581 .addReg(dest).addReg(oldval).addImm(0);
582 BuildMI(BB, dl, TII->get(AArch64::Bcc))
583 .addImm(A64CC::NE).addMBB(exitMBB);
584 BB->addSuccessor(loop2MBB);
585 BB->addSuccessor(exitMBB);
588 // strex stxr_status, newval, [ptr]
589 // cbnz stxr_status, loop1MBB
591 unsigned stxr_status = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
592 MRI.constrainRegClass(stxr_status, &AArch64::GPR32wspRegClass);
594 BuildMI(BB, dl, TII->get(strOpc), stxr_status).addReg(newval).addReg(ptr);
595 BuildMI(BB, dl, TII->get(AArch64::CBNZw))
596 .addReg(stxr_status).addMBB(loop1MBB);
597 BB->addSuccessor(loop1MBB);
598 BB->addSuccessor(exitMBB);
604 MI->eraseFromParent(); // The instruction is gone now.
610 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
611 MachineBasicBlock *MBB) const {
612 // We materialise the F128CSEL pseudo-instruction using conditional branches
613 // and loads, giving an instruciton sequence like:
622 // Using virtual registers would probably not be beneficial since COPY
623 // instructions are expensive for f128 (there's no actual instruction to
626 // An alternative would be to do an integer-CSEL on some address. E.g.:
631 // csel x0, x0, x1, ne
634 // It's unclear which approach is actually optimal.
635 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
636 MachineFunction *MF = MBB->getParent();
637 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
638 DebugLoc DL = MI->getDebugLoc();
639 MachineFunction::iterator It = MBB;
642 unsigned DestReg = MI->getOperand(0).getReg();
643 unsigned IfTrueReg = MI->getOperand(1).getReg();
644 unsigned IfFalseReg = MI->getOperand(2).getReg();
645 unsigned CondCode = MI->getOperand(3).getImm();
646 bool NZCVKilled = MI->getOperand(4).isKill();
648 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
649 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
650 MF->insert(It, TrueBB);
651 MF->insert(It, EndBB);
653 // Transfer rest of current basic-block to EndBB
654 EndBB->splice(EndBB->begin(), MBB,
655 llvm::next(MachineBasicBlock::iterator(MI)),
657 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
659 // We need somewhere to store the f128 value needed.
660 int ScratchFI = MF->getFrameInfo()->CreateSpillStackObject(16, 16);
662 // [... start of incoming MBB ...]
663 // str qIFFALSE, [sp]
666 BuildMI(MBB, DL, TII->get(AArch64::LSFP128_STR))
668 .addFrameIndex(ScratchFI)
670 BuildMI(MBB, DL, TII->get(AArch64::Bcc))
673 BuildMI(MBB, DL, TII->get(AArch64::Bimm))
675 MBB->addSuccessor(TrueBB);
676 MBB->addSuccessor(EndBB);
680 BuildMI(TrueBB, DL, TII->get(AArch64::LSFP128_STR))
682 .addFrameIndex(ScratchFI)
685 // Note: fallthrough. We can rely on LLVM adding a branch if it reorders the
687 TrueBB->addSuccessor(EndBB);
691 // [... rest of incoming MBB ...]
693 EndBB->addLiveIn(AArch64::NZCV);
694 MachineInstr *StartOfEnd = EndBB->begin();
695 BuildMI(*EndBB, StartOfEnd, DL, TII->get(AArch64::LSFP128_LDR), DestReg)
696 .addFrameIndex(ScratchFI)
699 MI->eraseFromParent();
704 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
705 MachineBasicBlock *MBB) const {
706 switch (MI->getOpcode()) {
707 default: llvm_unreachable("Unhandled instruction with custom inserter");
708 case AArch64::F128CSEL:
709 return EmitF128CSEL(MI, MBB);
710 case AArch64::ATOMIC_LOAD_ADD_I8:
711 return emitAtomicBinary(MI, MBB, 1, AArch64::ADDwww_lsl);
712 case AArch64::ATOMIC_LOAD_ADD_I16:
713 return emitAtomicBinary(MI, MBB, 2, AArch64::ADDwww_lsl);
714 case AArch64::ATOMIC_LOAD_ADD_I32:
715 return emitAtomicBinary(MI, MBB, 4, AArch64::ADDwww_lsl);
716 case AArch64::ATOMIC_LOAD_ADD_I64:
717 return emitAtomicBinary(MI, MBB, 8, AArch64::ADDxxx_lsl);
719 case AArch64::ATOMIC_LOAD_SUB_I8:
720 return emitAtomicBinary(MI, MBB, 1, AArch64::SUBwww_lsl);
721 case AArch64::ATOMIC_LOAD_SUB_I16:
722 return emitAtomicBinary(MI, MBB, 2, AArch64::SUBwww_lsl);
723 case AArch64::ATOMIC_LOAD_SUB_I32:
724 return emitAtomicBinary(MI, MBB, 4, AArch64::SUBwww_lsl);
725 case AArch64::ATOMIC_LOAD_SUB_I64:
726 return emitAtomicBinary(MI, MBB, 8, AArch64::SUBxxx_lsl);
728 case AArch64::ATOMIC_LOAD_AND_I8:
729 return emitAtomicBinary(MI, MBB, 1, AArch64::ANDwww_lsl);
730 case AArch64::ATOMIC_LOAD_AND_I16:
731 return emitAtomicBinary(MI, MBB, 2, AArch64::ANDwww_lsl);
732 case AArch64::ATOMIC_LOAD_AND_I32:
733 return emitAtomicBinary(MI, MBB, 4, AArch64::ANDwww_lsl);
734 case AArch64::ATOMIC_LOAD_AND_I64:
735 return emitAtomicBinary(MI, MBB, 8, AArch64::ANDxxx_lsl);
737 case AArch64::ATOMIC_LOAD_OR_I8:
738 return emitAtomicBinary(MI, MBB, 1, AArch64::ORRwww_lsl);
739 case AArch64::ATOMIC_LOAD_OR_I16:
740 return emitAtomicBinary(MI, MBB, 2, AArch64::ORRwww_lsl);
741 case AArch64::ATOMIC_LOAD_OR_I32:
742 return emitAtomicBinary(MI, MBB, 4, AArch64::ORRwww_lsl);
743 case AArch64::ATOMIC_LOAD_OR_I64:
744 return emitAtomicBinary(MI, MBB, 8, AArch64::ORRxxx_lsl);
746 case AArch64::ATOMIC_LOAD_XOR_I8:
747 return emitAtomicBinary(MI, MBB, 1, AArch64::EORwww_lsl);
748 case AArch64::ATOMIC_LOAD_XOR_I16:
749 return emitAtomicBinary(MI, MBB, 2, AArch64::EORwww_lsl);
750 case AArch64::ATOMIC_LOAD_XOR_I32:
751 return emitAtomicBinary(MI, MBB, 4, AArch64::EORwww_lsl);
752 case AArch64::ATOMIC_LOAD_XOR_I64:
753 return emitAtomicBinary(MI, MBB, 8, AArch64::EORxxx_lsl);
755 case AArch64::ATOMIC_LOAD_NAND_I8:
756 return emitAtomicBinary(MI, MBB, 1, AArch64::BICwww_lsl);
757 case AArch64::ATOMIC_LOAD_NAND_I16:
758 return emitAtomicBinary(MI, MBB, 2, AArch64::BICwww_lsl);
759 case AArch64::ATOMIC_LOAD_NAND_I32:
760 return emitAtomicBinary(MI, MBB, 4, AArch64::BICwww_lsl);
761 case AArch64::ATOMIC_LOAD_NAND_I64:
762 return emitAtomicBinary(MI, MBB, 8, AArch64::BICxxx_lsl);
764 case AArch64::ATOMIC_LOAD_MIN_I8:
765 return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_sxtb, A64CC::GT);
766 case AArch64::ATOMIC_LOAD_MIN_I16:
767 return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_sxth, A64CC::GT);
768 case AArch64::ATOMIC_LOAD_MIN_I32:
769 return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::GT);
770 case AArch64::ATOMIC_LOAD_MIN_I64:
771 return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::GT);
773 case AArch64::ATOMIC_LOAD_MAX_I8:
774 return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_sxtb, A64CC::LT);
775 case AArch64::ATOMIC_LOAD_MAX_I16:
776 return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_sxth, A64CC::LT);
777 case AArch64::ATOMIC_LOAD_MAX_I32:
778 return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::LT);
779 case AArch64::ATOMIC_LOAD_MAX_I64:
780 return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::LT);
782 case AArch64::ATOMIC_LOAD_UMIN_I8:
783 return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_uxtb, A64CC::HI);
784 case AArch64::ATOMIC_LOAD_UMIN_I16:
785 return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_uxth, A64CC::HI);
786 case AArch64::ATOMIC_LOAD_UMIN_I32:
787 return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::HI);
788 case AArch64::ATOMIC_LOAD_UMIN_I64:
789 return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::HI);
791 case AArch64::ATOMIC_LOAD_UMAX_I8:
792 return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_uxtb, A64CC::LO);
793 case AArch64::ATOMIC_LOAD_UMAX_I16:
794 return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_uxth, A64CC::LO);
795 case AArch64::ATOMIC_LOAD_UMAX_I32:
796 return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::LO);
797 case AArch64::ATOMIC_LOAD_UMAX_I64:
798 return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::LO);
800 case AArch64::ATOMIC_SWAP_I8:
801 return emitAtomicBinary(MI, MBB, 1, 0);
802 case AArch64::ATOMIC_SWAP_I16:
803 return emitAtomicBinary(MI, MBB, 2, 0);
804 case AArch64::ATOMIC_SWAP_I32:
805 return emitAtomicBinary(MI, MBB, 4, 0);
806 case AArch64::ATOMIC_SWAP_I64:
807 return emitAtomicBinary(MI, MBB, 8, 0);
809 case AArch64::ATOMIC_CMP_SWAP_I8:
810 return emitAtomicCmpSwap(MI, MBB, 1);
811 case AArch64::ATOMIC_CMP_SWAP_I16:
812 return emitAtomicCmpSwap(MI, MBB, 2);
813 case AArch64::ATOMIC_CMP_SWAP_I32:
814 return emitAtomicCmpSwap(MI, MBB, 4);
815 case AArch64::ATOMIC_CMP_SWAP_I64:
816 return emitAtomicCmpSwap(MI, MBB, 8);
821 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
823 case AArch64ISD::BR_CC: return "AArch64ISD::BR_CC";
824 case AArch64ISD::Call: return "AArch64ISD::Call";
825 case AArch64ISD::FPMOV: return "AArch64ISD::FPMOV";
826 case AArch64ISD::GOTLoad: return "AArch64ISD::GOTLoad";
827 case AArch64ISD::BFI: return "AArch64ISD::BFI";
828 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
829 case AArch64ISD::Ret: return "AArch64ISD::Ret";
830 case AArch64ISD::SBFX: return "AArch64ISD::SBFX";
831 case AArch64ISD::SELECT_CC: return "AArch64ISD::SELECT_CC";
832 case AArch64ISD::SETCC: return "AArch64ISD::SETCC";
833 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
834 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
835 case AArch64ISD::TLSDESCCALL: return "AArch64ISD::TLSDESCCALL";
836 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
837 case AArch64ISD::WrapperSmall: return "AArch64ISD::WrapperSmall";
839 case AArch64ISD::NEON_BSL:
840 return "AArch64ISD::NEON_BSL";
841 case AArch64ISD::NEON_MOVIMM:
842 return "AArch64ISD::NEON_MOVIMM";
843 case AArch64ISD::NEON_MVNIMM:
844 return "AArch64ISD::NEON_MVNIMM";
845 case AArch64ISD::NEON_FMOVIMM:
846 return "AArch64ISD::NEON_FMOVIMM";
847 case AArch64ISD::NEON_CMP:
848 return "AArch64ISD::NEON_CMP";
849 case AArch64ISD::NEON_CMPZ:
850 return "AArch64ISD::NEON_CMPZ";
851 case AArch64ISD::NEON_TST:
852 return "AArch64ISD::NEON_TST";
853 case AArch64ISD::NEON_DUPIMM:
854 return "AArch64ISD::NEON_DUPIMM";
855 case AArch64ISD::NEON_QSHLs:
856 return "AArch64ISD::NEON_QSHLs";
857 case AArch64ISD::NEON_QSHLu:
858 return "AArch64ISD::NEON_QSHLu";
864 static const uint16_t AArch64FPRArgRegs[] = {
865 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
866 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7
868 static const unsigned NumFPRArgRegs = llvm::array_lengthof(AArch64FPRArgRegs);
870 static const uint16_t AArch64ArgRegs[] = {
871 AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3,
872 AArch64::X4, AArch64::X5, AArch64::X6, AArch64::X7
874 static const unsigned NumArgRegs = llvm::array_lengthof(AArch64ArgRegs);
876 static bool CC_AArch64NoMoreRegs(unsigned ValNo, MVT ValVT, MVT LocVT,
877 CCValAssign::LocInfo LocInfo,
878 ISD::ArgFlagsTy ArgFlags, CCState &State) {
879 // Mark all remaining general purpose registers as allocated. We don't
880 // backtrack: if (for example) an i128 gets put on the stack, no subsequent
881 // i64 will go in registers (C.11).
882 for (unsigned i = 0; i < NumArgRegs; ++i)
883 State.AllocateReg(AArch64ArgRegs[i]);
888 #include "AArch64GenCallingConv.inc"
890 CCAssignFn *AArch64TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
893 default: llvm_unreachable("Unsupported calling convention");
894 case CallingConv::Fast:
901 AArch64TargetLowering::SaveVarArgRegisters(CCState &CCInfo, SelectionDAG &DAG,
902 SDLoc DL, SDValue &Chain) const {
903 MachineFunction &MF = DAG.getMachineFunction();
904 MachineFrameInfo *MFI = MF.getFrameInfo();
905 AArch64MachineFunctionInfo *FuncInfo
906 = MF.getInfo<AArch64MachineFunctionInfo>();
908 SmallVector<SDValue, 8> MemOps;
910 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(AArch64ArgRegs,
912 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(AArch64FPRArgRegs,
915 unsigned GPRSaveSize = 8 * (NumArgRegs - FirstVariadicGPR);
917 if (GPRSaveSize != 0) {
918 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
920 SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
922 for (unsigned i = FirstVariadicGPR; i < NumArgRegs; ++i) {
923 unsigned VReg = MF.addLiveIn(AArch64ArgRegs[i], &AArch64::GPR64RegClass);
924 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
925 SDValue Store = DAG.getStore(Val.getValue(1), DL, Val, FIN,
926 MachinePointerInfo::getStack(i * 8),
928 MemOps.push_back(Store);
929 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
930 DAG.getConstant(8, getPointerTy()));
934 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
936 if (FPRSaveSize != 0) {
937 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
939 SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
941 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
942 unsigned VReg = MF.addLiveIn(AArch64FPRArgRegs[i],
943 &AArch64::FPR128RegClass);
944 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
945 SDValue Store = DAG.getStore(Val.getValue(1), DL, Val, FIN,
946 MachinePointerInfo::getStack(i * 16),
948 MemOps.push_back(Store);
949 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
950 DAG.getConstant(16, getPointerTy()));
954 int StackIdx = MFI->CreateFixedObject(8, CCInfo.getNextStackOffset(), true);
956 FuncInfo->setVariadicStackIdx(StackIdx);
957 FuncInfo->setVariadicGPRIdx(GPRIdx);
958 FuncInfo->setVariadicGPRSize(GPRSaveSize);
959 FuncInfo->setVariadicFPRIdx(FPRIdx);
960 FuncInfo->setVariadicFPRSize(FPRSaveSize);
962 if (!MemOps.empty()) {
963 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
970 AArch64TargetLowering::LowerFormalArguments(SDValue Chain,
971 CallingConv::ID CallConv, bool isVarArg,
972 const SmallVectorImpl<ISD::InputArg> &Ins,
973 SDLoc dl, SelectionDAG &DAG,
974 SmallVectorImpl<SDValue> &InVals) const {
975 MachineFunction &MF = DAG.getMachineFunction();
976 AArch64MachineFunctionInfo *FuncInfo
977 = MF.getInfo<AArch64MachineFunctionInfo>();
978 MachineFrameInfo *MFI = MF.getFrameInfo();
979 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
981 SmallVector<CCValAssign, 16> ArgLocs;
982 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
983 getTargetMachine(), ArgLocs, *DAG.getContext());
984 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
986 SmallVector<SDValue, 16> ArgValues;
989 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
990 CCValAssign &VA = ArgLocs[i];
991 ISD::ArgFlagsTy Flags = Ins[i].Flags;
993 if (Flags.isByVal()) {
994 // Byval is used for small structs and HFAs in the PCS, but the system
995 // should work in a non-compliant manner for larger structs.
996 EVT PtrTy = getPointerTy();
997 int Size = Flags.getByValSize();
998 unsigned NumRegs = (Size + 7) / 8;
1000 unsigned FrameIdx = MFI->CreateFixedObject(8 * NumRegs,
1001 VA.getLocMemOffset(),
1003 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrTy);
1004 InVals.push_back(FrameIdxN);
1007 } else if (VA.isRegLoc()) {
1008 MVT RegVT = VA.getLocVT();
1009 const TargetRegisterClass *RC = getRegClassFor(RegVT);
1010 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1012 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1013 } else { // VA.isRegLoc()
1014 assert(VA.isMemLoc());
1016 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
1017 VA.getLocMemOffset(), true);
1019 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1020 ArgValue = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1021 MachinePointerInfo::getFixedStack(FI),
1022 false, false, false, 0);
1027 switch (VA.getLocInfo()) {
1028 default: llvm_unreachable("Unknown loc info!");
1029 case CCValAssign::Full: break;
1030 case CCValAssign::BCvt:
1031 ArgValue = DAG.getNode(ISD::BITCAST,dl, VA.getValVT(), ArgValue);
1033 case CCValAssign::SExt:
1034 case CCValAssign::ZExt:
1035 case CCValAssign::AExt: {
1036 unsigned DestSize = VA.getValVT().getSizeInBits();
1037 unsigned DestSubReg;
1040 case 8: DestSubReg = AArch64::sub_8; break;
1041 case 16: DestSubReg = AArch64::sub_16; break;
1042 case 32: DestSubReg = AArch64::sub_32; break;
1043 case 64: DestSubReg = AArch64::sub_64; break;
1044 default: llvm_unreachable("Unexpected argument promotion");
1047 ArgValue = SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl,
1048 VA.getValVT(), ArgValue,
1049 DAG.getTargetConstant(DestSubReg, MVT::i32)),
1055 InVals.push_back(ArgValue);
1059 SaveVarArgRegisters(CCInfo, DAG, dl, Chain);
1061 unsigned StackArgSize = CCInfo.getNextStackOffset();
1062 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
1063 // This is a non-standard ABI so by fiat I say we're allowed to make full
1064 // use of the stack area to be popped, which must be aligned to 16 bytes in
1066 StackArgSize = RoundUpToAlignment(StackArgSize, 16);
1068 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
1069 // a multiple of 16.
1070 FuncInfo->setArgumentStackToRestore(StackArgSize);
1072 // This realignment carries over to the available bytes below. Our own
1073 // callers will guarantee the space is free by giving an aligned value to
1076 // Even if we're not expected to free up the space, it's useful to know how
1077 // much is there while considering tail calls (because we can reuse it).
1078 FuncInfo->setBytesInStackArgArea(StackArgSize);
1084 AArch64TargetLowering::LowerReturn(SDValue Chain,
1085 CallingConv::ID CallConv, bool isVarArg,
1086 const SmallVectorImpl<ISD::OutputArg> &Outs,
1087 const SmallVectorImpl<SDValue> &OutVals,
1088 SDLoc dl, SelectionDAG &DAG) const {
1089 // CCValAssign - represent the assignment of the return value to a location.
1090 SmallVector<CCValAssign, 16> RVLocs;
1092 // CCState - Info about the registers and stack slots.
1093 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1094 getTargetMachine(), RVLocs, *DAG.getContext());
1096 // Analyze outgoing return values.
1097 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv));
1100 SmallVector<SDValue, 4> RetOps(1, Chain);
1102 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1103 // PCS: "If the type, T, of the result of a function is such that
1104 // void func(T arg) would require that arg be passed as a value in a
1105 // register (or set of registers) according to the rules in 5.4, then the
1106 // result is returned in the same registers as would be used for such an
1109 // Otherwise, the caller shall reserve a block of memory of sufficient
1110 // size and alignment to hold the result. The address of the memory block
1111 // shall be passed as an additional argument to the function in x8."
1113 // This is implemented in two places. The register-return values are dealt
1114 // with here, more complex returns are passed as an sret parameter, which
1115 // means we don't have to worry about it during actual return.
1116 CCValAssign &VA = RVLocs[i];
1117 assert(VA.isRegLoc() && "Only register-returns should be created by PCS");
1120 SDValue Arg = OutVals[i];
1122 // There's no convenient note in the ABI about this as there is for normal
1123 // arguments, but it says return values are passed in the same registers as
1124 // an argument would be. I believe that includes the comments about
1125 // unspecified higher bits, putting the burden of widening on the *caller*
1126 // for return values.
1127 switch (VA.getLocInfo()) {
1128 default: llvm_unreachable("Unknown loc info");
1129 case CCValAssign::Full: break;
1130 case CCValAssign::SExt:
1131 case CCValAssign::ZExt:
1132 case CCValAssign::AExt:
1133 // Floating-point values should only be extended when they're going into
1134 // memory, which can't happen here so an integer extend is acceptable.
1135 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1137 case CCValAssign::BCvt:
1138 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1142 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1143 Flag = Chain.getValue(1);
1144 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1147 RetOps[0] = Chain; // Update chain.
1149 // Add the flag if we have it.
1151 RetOps.push_back(Flag);
1153 return DAG.getNode(AArch64ISD::Ret, dl, MVT::Other,
1154 &RetOps[0], RetOps.size());
1158 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
1159 SmallVectorImpl<SDValue> &InVals) const {
1160 SelectionDAG &DAG = CLI.DAG;
1162 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1163 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1164 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1165 SDValue Chain = CLI.Chain;
1166 SDValue Callee = CLI.Callee;
1167 bool &IsTailCall = CLI.IsTailCall;
1168 CallingConv::ID CallConv = CLI.CallConv;
1169 bool IsVarArg = CLI.IsVarArg;
1171 MachineFunction &MF = DAG.getMachineFunction();
1172 AArch64MachineFunctionInfo *FuncInfo
1173 = MF.getInfo<AArch64MachineFunctionInfo>();
1174 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
1175 bool IsStructRet = !Outs.empty() && Outs[0].Flags.isSRet();
1176 bool IsSibCall = false;
1179 IsTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1180 IsVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1181 Outs, OutVals, Ins, DAG);
1183 // A sibling call is one where we're under the usual C ABI and not planning
1184 // to change that but can still do a tail call:
1185 if (!TailCallOpt && IsTailCall)
1189 SmallVector<CCValAssign, 16> ArgLocs;
1190 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
1191 getTargetMachine(), ArgLocs, *DAG.getContext());
1192 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1194 // On AArch64 (and all other architectures I'm aware of) the most this has to
1195 // do is adjust the stack pointer.
1196 unsigned NumBytes = RoundUpToAlignment(CCInfo.getNextStackOffset(), 16);
1198 // Since we're not changing the ABI to make this a tail call, the memory
1199 // operands are already available in the caller's incoming argument space.
1203 // FPDiff is the byte offset of the call's argument area from the callee's.
1204 // Stores to callee stack arguments will be placed in FixedStackSlots offset
1205 // by this amount for a tail call. In a sibling call it must be 0 because the
1206 // caller will deallocate the entire stack and the callee still expects its
1207 // arguments to begin at SP+0. Completely unused for non-tail calls.
1210 if (IsTailCall && !IsSibCall) {
1211 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
1213 // FPDiff will be negative if this tail call requires more space than we
1214 // would automatically have in our incoming argument space. Positive if we
1215 // can actually shrink the stack.
1216 FPDiff = NumReusableBytes - NumBytes;
1218 // The stack pointer must be 16-byte aligned at all times it's used for a
1219 // memory operation, which in practice means at *all* times and in
1220 // particular across call boundaries. Therefore our own arguments started at
1221 // a 16-byte aligned SP and the delta applied for the tail call should
1222 // satisfy the same constraint.
1223 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
1227 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1230 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, AArch64::XSP,
1233 SmallVector<SDValue, 8> MemOpChains;
1234 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1236 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1237 CCValAssign &VA = ArgLocs[i];
1238 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1239 SDValue Arg = OutVals[i];
1241 // Callee does the actual widening, so all extensions just use an implicit
1242 // definition of the rest of the Loc. Aesthetically, this would be nicer as
1243 // an ANY_EXTEND, but that isn't valid for floating-point types and this
1244 // alternative works on integer types too.
1245 switch (VA.getLocInfo()) {
1246 default: llvm_unreachable("Unknown loc info!");
1247 case CCValAssign::Full: break;
1248 case CCValAssign::SExt:
1249 case CCValAssign::ZExt:
1250 case CCValAssign::AExt: {
1251 unsigned SrcSize = VA.getValVT().getSizeInBits();
1255 case 8: SrcSubReg = AArch64::sub_8; break;
1256 case 16: SrcSubReg = AArch64::sub_16; break;
1257 case 32: SrcSubReg = AArch64::sub_32; break;
1258 case 64: SrcSubReg = AArch64::sub_64; break;
1259 default: llvm_unreachable("Unexpected argument promotion");
1262 Arg = SDValue(DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl,
1264 DAG.getUNDEF(VA.getLocVT()),
1266 DAG.getTargetConstant(SrcSubReg, MVT::i32)),
1271 case CCValAssign::BCvt:
1272 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1276 if (VA.isRegLoc()) {
1277 // A normal register (sub-) argument. For now we just note it down because
1278 // we want to copy things into registers as late as possible to avoid
1279 // register-pressure (and possibly worse).
1280 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1284 assert(VA.isMemLoc() && "unexpected argument location");
1287 MachinePointerInfo DstInfo;
1289 uint32_t OpSize = Flags.isByVal() ? Flags.getByValSize() :
1290 VA.getLocVT().getSizeInBits();
1291 OpSize = (OpSize + 7) / 8;
1292 int32_t Offset = VA.getLocMemOffset() + FPDiff;
1293 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
1295 DstAddr = DAG.getFrameIndex(FI, getPointerTy());
1296 DstInfo = MachinePointerInfo::getFixedStack(FI);
1298 // Make sure any stack arguments overlapping with where we're storing are
1299 // loaded before this eventual operation. Otherwise they'll be clobbered.
1300 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
1302 SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset());
1304 DstAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1305 DstInfo = MachinePointerInfo::getStack(VA.getLocMemOffset());
1308 if (Flags.isByVal()) {
1309 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i64);
1310 SDValue Cpy = DAG.getMemcpy(Chain, dl, DstAddr, Arg, SizeNode,
1311 Flags.getByValAlign(),
1312 /*isVolatile = */ false,
1313 /*alwaysInline = */ false,
1314 DstInfo, MachinePointerInfo(0));
1315 MemOpChains.push_back(Cpy);
1317 // Normal stack argument, put it where it's needed.
1318 SDValue Store = DAG.getStore(Chain, dl, Arg, DstAddr, DstInfo,
1320 MemOpChains.push_back(Store);
1324 // The loads and stores generated above shouldn't clash with each
1325 // other. Combining them with this TokenFactor notes that fact for the rest of
1327 if (!MemOpChains.empty())
1328 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1329 &MemOpChains[0], MemOpChains.size());
1331 // Most of the rest of the instructions need to be glued together; we don't
1332 // want assignments to actual registers used by a call to be rearranged by a
1333 // well-meaning scheduler.
1336 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1337 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1338 RegsToPass[i].second, InFlag);
1339 InFlag = Chain.getValue(1);
1342 // The linker is responsible for inserting veneers when necessary to put a
1343 // function call destination in range, so we don't need to bother with a
1345 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1346 const GlobalValue *GV = G->getGlobal();
1347 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy());
1348 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1349 const char *Sym = S->getSymbol();
1350 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy());
1353 // We don't usually want to end the call-sequence here because we would tidy
1354 // the frame up *after* the call, however in the ABI-changing tail-call case
1355 // we've carefully laid out the parameters so that when sp is reset they'll be
1356 // in the correct location.
1357 if (IsTailCall && !IsSibCall) {
1358 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1359 DAG.getIntPtrConstant(0, true), InFlag, dl);
1360 InFlag = Chain.getValue(1);
1363 // We produce the following DAG scheme for the actual call instruction:
1364 // (AArch64Call Chain, Callee, reg1, ..., regn, preserveMask, inflag?
1366 // Most arguments aren't going to be used and just keep the values live as
1367 // far as LLVM is concerned. It's expected to be selected as simply "bl
1368 // callee" (for a direct, non-tail call).
1369 std::vector<SDValue> Ops;
1370 Ops.push_back(Chain);
1371 Ops.push_back(Callee);
1374 // Each tail call may have to adjust the stack by a different amount, so
1375 // this information must travel along with the operation for eventual
1376 // consumption by emitEpilogue.
1377 Ops.push_back(DAG.getTargetConstant(FPDiff, MVT::i32));
1380 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1381 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1382 RegsToPass[i].second.getValueType()));
1385 // Add a register mask operand representing the call-preserved registers. This
1386 // is used later in codegen to constrain register-allocation.
1387 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1388 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1389 assert(Mask && "Missing call preserved mask for calling convention");
1390 Ops.push_back(DAG.getRegisterMask(Mask));
1392 // If we needed glue, put it in as the last argument.
1393 if (InFlag.getNode())
1394 Ops.push_back(InFlag);
1396 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1399 return DAG.getNode(AArch64ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1402 Chain = DAG.getNode(AArch64ISD::Call, dl, NodeTys, &Ops[0], Ops.size());
1403 InFlag = Chain.getValue(1);
1405 // Now we can reclaim the stack, just as well do it before working out where
1406 // our return value is.
1408 uint64_t CalleePopBytes
1409 = DoesCalleeRestoreStack(CallConv, TailCallOpt) ? NumBytes : 0;
1411 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1412 DAG.getIntPtrConstant(CalleePopBytes, true),
1414 InFlag = Chain.getValue(1);
1417 return LowerCallResult(Chain, InFlag, CallConv,
1418 IsVarArg, Ins, dl, DAG, InVals);
1422 AArch64TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1423 CallingConv::ID CallConv, bool IsVarArg,
1424 const SmallVectorImpl<ISD::InputArg> &Ins,
1425 SDLoc dl, SelectionDAG &DAG,
1426 SmallVectorImpl<SDValue> &InVals) const {
1427 // Assign locations to each value returned by this call.
1428 SmallVector<CCValAssign, 16> RVLocs;
1429 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
1430 getTargetMachine(), RVLocs, *DAG.getContext());
1431 CCInfo.AnalyzeCallResult(Ins, CCAssignFnForNode(CallConv));
1433 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1434 CCValAssign VA = RVLocs[i];
1436 // Return values that are too big to fit into registers should use an sret
1437 // pointer, so this can be a lot simpler than the main argument code.
1438 assert(VA.isRegLoc() && "Memory locations not expected for call return");
1440 SDValue Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1442 Chain = Val.getValue(1);
1443 InFlag = Val.getValue(2);
1445 switch (VA.getLocInfo()) {
1446 default: llvm_unreachable("Unknown loc info!");
1447 case CCValAssign::Full: break;
1448 case CCValAssign::BCvt:
1449 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1451 case CCValAssign::ZExt:
1452 case CCValAssign::SExt:
1453 case CCValAssign::AExt:
1454 // Floating-point arguments only get extended/truncated if they're going
1455 // in memory, so using the integer operation is acceptable here.
1456 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
1460 InVals.push_back(Val);
1467 AArch64TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1468 CallingConv::ID CalleeCC,
1470 bool IsCalleeStructRet,
1471 bool IsCallerStructRet,
1472 const SmallVectorImpl<ISD::OutputArg> &Outs,
1473 const SmallVectorImpl<SDValue> &OutVals,
1474 const SmallVectorImpl<ISD::InputArg> &Ins,
1475 SelectionDAG& DAG) const {
1477 // For CallingConv::C this function knows whether the ABI needs
1478 // changing. That's not true for other conventions so they will have to opt in
1480 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1483 const MachineFunction &MF = DAG.getMachineFunction();
1484 const Function *CallerF = MF.getFunction();
1485 CallingConv::ID CallerCC = CallerF->getCallingConv();
1486 bool CCMatch = CallerCC == CalleeCC;
1488 // Byval parameters hand the function a pointer directly into the stack area
1489 // we want to reuse during a tail call. Working around this *is* possible (see
1490 // X86) but less efficient and uglier in LowerCall.
1491 for (Function::const_arg_iterator i = CallerF->arg_begin(),
1492 e = CallerF->arg_end(); i != e; ++i)
1493 if (i->hasByValAttr())
1496 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
1497 if (IsTailCallConvention(CalleeCC) && CCMatch)
1502 // Now we search for cases where we can use a tail call without changing the
1503 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
1506 // I want anyone implementing a new calling convention to think long and hard
1507 // about this assert.
1508 assert((!IsVarArg || CalleeCC == CallingConv::C)
1509 && "Unexpected variadic calling convention");
1511 if (IsVarArg && !Outs.empty()) {
1512 // At least two cases here: if caller is fastcc then we can't have any
1513 // memory arguments (we'd be expected to clean up the stack afterwards). If
1514 // caller is C then we could potentially use its argument area.
1516 // FIXME: for now we take the most conservative of these in both cases:
1517 // disallow all variadic memory operands.
1518 SmallVector<CCValAssign, 16> ArgLocs;
1519 CCState CCInfo(CalleeCC, IsVarArg, DAG.getMachineFunction(),
1520 getTargetMachine(), ArgLocs, *DAG.getContext());
1522 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
1523 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
1524 if (!ArgLocs[i].isRegLoc())
1528 // If the calling conventions do not match, then we'd better make sure the
1529 // results are returned in the same way as what the caller expects.
1531 SmallVector<CCValAssign, 16> RVLocs1;
1532 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1533 getTargetMachine(), RVLocs1, *DAG.getContext());
1534 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC));
1536 SmallVector<CCValAssign, 16> RVLocs2;
1537 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1538 getTargetMachine(), RVLocs2, *DAG.getContext());
1539 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC));
1541 if (RVLocs1.size() != RVLocs2.size())
1543 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1544 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1546 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1548 if (RVLocs1[i].isRegLoc()) {
1549 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1552 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1558 // Nothing more to check if the callee is taking no arguments
1562 SmallVector<CCValAssign, 16> ArgLocs;
1563 CCState CCInfo(CalleeCC, IsVarArg, DAG.getMachineFunction(),
1564 getTargetMachine(), ArgLocs, *DAG.getContext());
1566 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
1568 const AArch64MachineFunctionInfo *FuncInfo
1569 = MF.getInfo<AArch64MachineFunctionInfo>();
1571 // If the stack arguments for this call would fit into our own save area then
1572 // the call can be made tail.
1573 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
1576 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
1577 bool TailCallOpt) const {
1578 return CallCC == CallingConv::Fast && TailCallOpt;
1581 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
1582 return CallCC == CallingConv::Fast;
1585 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
1587 MachineFrameInfo *MFI,
1588 int ClobberedFI) const {
1589 SmallVector<SDValue, 8> ArgChains;
1590 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
1591 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
1593 // Include the original chain at the beginning of the list. When this is
1594 // used by target LowerCall hooks, this helps legalize find the
1595 // CALLSEQ_BEGIN node.
1596 ArgChains.push_back(Chain);
1598 // Add a chain value for each stack argument corresponding
1599 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
1600 UE = DAG.getEntryNode().getNode()->use_end(); U != UE; ++U)
1601 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
1602 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
1603 if (FI->getIndex() < 0) {
1604 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
1605 int64_t InLastByte = InFirstByte;
1606 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
1608 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
1609 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
1610 ArgChains.push_back(SDValue(L, 1));
1613 // Build a tokenfactor for all the chains.
1614 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other,
1615 &ArgChains[0], ArgChains.size());
1618 static A64CC::CondCodes IntCCToA64CC(ISD::CondCode CC) {
1620 case ISD::SETEQ: return A64CC::EQ;
1621 case ISD::SETGT: return A64CC::GT;
1622 case ISD::SETGE: return A64CC::GE;
1623 case ISD::SETLT: return A64CC::LT;
1624 case ISD::SETLE: return A64CC::LE;
1625 case ISD::SETNE: return A64CC::NE;
1626 case ISD::SETUGT: return A64CC::HI;
1627 case ISD::SETUGE: return A64CC::HS;
1628 case ISD::SETULT: return A64CC::LO;
1629 case ISD::SETULE: return A64CC::LS;
1630 default: llvm_unreachable("Unexpected condition code");
1634 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Val) const {
1635 // icmp is implemented using adds/subs immediate, which take an unsigned
1636 // 12-bit immediate, optionally shifted left by 12 bits.
1638 // Symmetric by using adds/subs
1642 return (Val & ~0xfff) == 0 || (Val & ~0xfff000) == 0;
1645 SDValue AArch64TargetLowering::getSelectableIntSetCC(SDValue LHS, SDValue RHS,
1646 ISD::CondCode CC, SDValue &A64cc,
1647 SelectionDAG &DAG, SDLoc &dl) const {
1648 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1650 EVT VT = RHSC->getValueType(0);
1651 bool knownInvalid = false;
1653 // I'm not convinced the rest of LLVM handles these edge cases properly, but
1654 // we can at least get it right.
1655 if (isSignedIntSetCC(CC)) {
1656 C = RHSC->getSExtValue();
1657 } else if (RHSC->getZExtValue() > INT64_MAX) {
1658 // A 64-bit constant not representable by a signed 64-bit integer is far
1659 // too big to fit into a SUBS immediate anyway.
1660 knownInvalid = true;
1662 C = RHSC->getZExtValue();
1665 if (!knownInvalid && !isLegalICmpImmediate(C)) {
1666 // Constant does not fit, try adjusting it by one?
1671 if (isLegalICmpImmediate(C-1)) {
1672 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1673 RHS = DAG.getConstant(C-1, VT);
1678 if (isLegalICmpImmediate(C-1)) {
1679 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1680 RHS = DAG.getConstant(C-1, VT);
1685 if (isLegalICmpImmediate(C+1)) {
1686 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1687 RHS = DAG.getConstant(C+1, VT);
1692 if (isLegalICmpImmediate(C+1)) {
1693 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1694 RHS = DAG.getConstant(C+1, VT);
1701 A64CC::CondCodes CondCode = IntCCToA64CC(CC);
1702 A64cc = DAG.getConstant(CondCode, MVT::i32);
1703 return DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
1704 DAG.getCondCode(CC));
1707 static A64CC::CondCodes FPCCToA64CC(ISD::CondCode CC,
1708 A64CC::CondCodes &Alternative) {
1709 A64CC::CondCodes CondCode = A64CC::Invalid;
1710 Alternative = A64CC::Invalid;
1713 default: llvm_unreachable("Unknown FP condition!");
1715 case ISD::SETOEQ: CondCode = A64CC::EQ; break;
1717 case ISD::SETOGT: CondCode = A64CC::GT; break;
1719 case ISD::SETOGE: CondCode = A64CC::GE; break;
1720 case ISD::SETOLT: CondCode = A64CC::MI; break;
1721 case ISD::SETOLE: CondCode = A64CC::LS; break;
1722 case ISD::SETONE: CondCode = A64CC::MI; Alternative = A64CC::GT; break;
1723 case ISD::SETO: CondCode = A64CC::VC; break;
1724 case ISD::SETUO: CondCode = A64CC::VS; break;
1725 case ISD::SETUEQ: CondCode = A64CC::EQ; Alternative = A64CC::VS; break;
1726 case ISD::SETUGT: CondCode = A64CC::HI; break;
1727 case ISD::SETUGE: CondCode = A64CC::PL; break;
1729 case ISD::SETULT: CondCode = A64CC::LT; break;
1731 case ISD::SETULE: CondCode = A64CC::LE; break;
1733 case ISD::SETUNE: CondCode = A64CC::NE; break;
1739 AArch64TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
1741 EVT PtrVT = getPointerTy();
1742 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1744 switch(getTargetMachine().getCodeModel()) {
1745 case CodeModel::Small:
1746 // The most efficient code is PC-relative anyway for the small memory model,
1747 // so we don't need to worry about relocation model.
1748 return DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
1749 DAG.getTargetBlockAddress(BA, PtrVT, 0,
1750 AArch64II::MO_NO_FLAG),
1751 DAG.getTargetBlockAddress(BA, PtrVT, 0,
1752 AArch64II::MO_LO12),
1753 DAG.getConstant(/*Alignment=*/ 4, MVT::i32));
1754 case CodeModel::Large:
1756 AArch64ISD::WrapperLarge, DL, PtrVT,
1757 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G3),
1758 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G2_NC),
1759 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G1_NC),
1760 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G0_NC));
1762 llvm_unreachable("Only small and large code models supported now");
1767 // (BRCOND chain, val, dest)
1769 AArch64TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1771 SDValue Chain = Op.getOperand(0);
1772 SDValue TheBit = Op.getOperand(1);
1773 SDValue DestBB = Op.getOperand(2);
1775 // AArch64 BooleanContents is the default UndefinedBooleanContent, which means
1776 // that as the consumer we are responsible for ignoring rubbish in higher
1778 TheBit = DAG.getNode(ISD::AND, dl, MVT::i32, TheBit,
1779 DAG.getConstant(1, MVT::i32));
1781 SDValue A64CMP = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, TheBit,
1782 DAG.getConstant(0, TheBit.getValueType()),
1783 DAG.getCondCode(ISD::SETNE));
1785 return DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other, Chain,
1786 A64CMP, DAG.getConstant(A64CC::NE, MVT::i32),
1790 // (BR_CC chain, condcode, lhs, rhs, dest)
1792 AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
1794 SDValue Chain = Op.getOperand(0);
1795 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1796 SDValue LHS = Op.getOperand(2);
1797 SDValue RHS = Op.getOperand(3);
1798 SDValue DestBB = Op.getOperand(4);
1800 if (LHS.getValueType() == MVT::f128) {
1801 // f128 comparisons are lowered to runtime calls by a routine which sets
1802 // LHS, RHS and CC appropriately for the rest of this function to continue.
1803 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
1805 // If softenSetCCOperands returned a scalar, we need to compare the result
1806 // against zero to select between true and false values.
1807 if (RHS.getNode() == 0) {
1808 RHS = DAG.getConstant(0, LHS.getValueType());
1813 if (LHS.getValueType().isInteger()) {
1816 // Integers are handled in a separate function because the combinations of
1817 // immediates and tests can get hairy and we may want to fiddle things.
1818 SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
1820 return DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
1821 Chain, CmpOp, A64cc, DestBB);
1824 // Note that some LLVM floating-point CondCodes can't be lowered to a single
1825 // conditional branch, hence FPCCToA64CC can set a second test, where either
1826 // passing is sufficient.
1827 A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
1828 CondCode = FPCCToA64CC(CC, Alternative);
1829 SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
1830 SDValue SetCC = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
1831 DAG.getCondCode(CC));
1832 SDValue A64BR_CC = DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
1833 Chain, SetCC, A64cc, DestBB);
1835 if (Alternative != A64CC::Invalid) {
1836 A64cc = DAG.getConstant(Alternative, MVT::i32);
1837 A64BR_CC = DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
1838 A64BR_CC, SetCC, A64cc, DestBB);
1846 AArch64TargetLowering::LowerF128ToCall(SDValue Op, SelectionDAG &DAG,
1847 RTLIB::Libcall Call) const {
1850 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
1851 EVT ArgVT = Op.getOperand(i).getValueType();
1852 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1853 Entry.Node = Op.getOperand(i); Entry.Ty = ArgTy;
1854 Entry.isSExt = false;
1855 Entry.isZExt = false;
1856 Args.push_back(Entry);
1858 SDValue Callee = DAG.getExternalSymbol(getLibcallName(Call), getPointerTy());
1860 Type *RetTy = Op.getValueType().getTypeForEVT(*DAG.getContext());
1862 // By default, the input chain to this libcall is the entry node of the
1863 // function. If the libcall is going to be emitted as a tail call then
1864 // isUsedByReturnOnly will change it to the right chain if the return
1865 // node which is being folded has a non-entry input chain.
1866 SDValue InChain = DAG.getEntryNode();
1868 // isTailCall may be true since the callee does not reference caller stack
1869 // frame. Check if it's in the right position.
1870 SDValue TCChain = InChain;
1871 bool isTailCall = isInTailCallPosition(DAG, Op.getNode(), TCChain);
1876 CallLoweringInfo CLI(InChain, RetTy, false, false, false, false,
1877 0, getLibcallCallingConv(Call), isTailCall,
1878 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
1879 Callee, Args, DAG, SDLoc(Op));
1880 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
1882 if (!CallInfo.second.getNode())
1883 // It's a tailcall, return the chain (which is the DAG root).
1884 return DAG.getRoot();
1886 return CallInfo.first;
1890 AArch64TargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
1891 if (Op.getOperand(0).getValueType() != MVT::f128) {
1892 // It's legal except when f128 is involved
1897 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1899 SDValue SrcVal = Op.getOperand(0);
1900 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1901 /*isSigned*/ false, SDLoc(Op)).first;
1905 AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
1906 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1909 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1911 return LowerF128ToCall(Op, DAG, LC);
1915 AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
1916 bool IsSigned) const {
1917 if (Op.getOperand(0).getValueType() != MVT::f128) {
1918 // It's legal except when f128 is involved
1924 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1926 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1928 return LowerF128ToCall(Op, DAG, LC);
1932 AArch64TargetLowering::LowerGlobalAddressELFLarge(SDValue Op,
1933 SelectionDAG &DAG) const {
1934 assert(getTargetMachine().getCodeModel() == CodeModel::Large);
1935 assert(getTargetMachine().getRelocationModel() == Reloc::Static);
1937 EVT PtrVT = getPointerTy();
1939 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
1940 const GlobalValue *GV = GN->getGlobal();
1942 SDValue GlobalAddr = DAG.getNode(
1943 AArch64ISD::WrapperLarge, dl, PtrVT,
1944 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G3),
1945 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G2_NC),
1946 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G1_NC),
1947 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G0_NC));
1949 if (GN->getOffset() != 0)
1950 return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalAddr,
1951 DAG.getConstant(GN->getOffset(), PtrVT));
1957 AArch64TargetLowering::LowerGlobalAddressELFSmall(SDValue Op,
1958 SelectionDAG &DAG) const {
1959 assert(getTargetMachine().getCodeModel() == CodeModel::Small);
1961 EVT PtrVT = getPointerTy();
1963 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
1964 const GlobalValue *GV = GN->getGlobal();
1965 unsigned Alignment = GV->getAlignment();
1966 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1967 if (GV->isWeakForLinker() && GV->isDeclaration() && RelocM == Reloc::Static) {
1968 // Weak undefined symbols can't use ADRP/ADD pair since they should evaluate
1969 // to zero when they remain undefined. In PIC mode the GOT can take care of
1970 // this, but in absolute mode we use a constant pool load.
1972 PoolAddr = DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
1973 DAG.getTargetConstantPool(GV, PtrVT, 0, 0,
1974 AArch64II::MO_NO_FLAG),
1975 DAG.getTargetConstantPool(GV, PtrVT, 0, 0,
1976 AArch64II::MO_LO12),
1977 DAG.getConstant(8, MVT::i32));
1978 SDValue GlobalAddr = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), PoolAddr,
1979 MachinePointerInfo::getConstantPool(),
1980 /*isVolatile=*/ false,
1981 /*isNonTemporal=*/ true,
1982 /*isInvariant=*/ true, 8);
1983 if (GN->getOffset() != 0)
1984 return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalAddr,
1985 DAG.getConstant(GN->getOffset(), PtrVT));
1990 if (Alignment == 0) {
1991 const PointerType *GVPtrTy = cast<PointerType>(GV->getType());
1992 if (GVPtrTy->getElementType()->isSized()) {
1994 = getDataLayout()->getABITypeAlignment(GVPtrTy->getElementType());
1996 // Be conservative if we can't guess, not that it really matters:
1997 // functions and labels aren't valid for loads, and the methods used to
1998 // actually calculate an address work with any alignment.
2003 unsigned char HiFixup, LoFixup;
2004 bool UseGOT = getSubtarget()->GVIsIndirectSymbol(GV, RelocM);
2007 HiFixup = AArch64II::MO_GOT;
2008 LoFixup = AArch64II::MO_GOT_LO12;
2011 HiFixup = AArch64II::MO_NO_FLAG;
2012 LoFixup = AArch64II::MO_LO12;
2015 // AArch64's small model demands the following sequence:
2016 // ADRP x0, somewhere
2017 // ADD x0, x0, #:lo12:somewhere ; (or LDR directly).
2018 SDValue GlobalRef = DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2019 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2021 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2023 DAG.getConstant(Alignment, MVT::i32));
2026 GlobalRef = DAG.getNode(AArch64ISD::GOTLoad, dl, PtrVT, DAG.getEntryNode(),
2030 if (GN->getOffset() != 0)
2031 return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalRef,
2032 DAG.getConstant(GN->getOffset(), PtrVT));
2038 AArch64TargetLowering::LowerGlobalAddressELF(SDValue Op,
2039 SelectionDAG &DAG) const {
2040 // TableGen doesn't have easy access to the CodeModel or RelocationModel, so
2041 // we make those distinctions here.
2043 switch (getTargetMachine().getCodeModel()) {
2044 case CodeModel::Small:
2045 return LowerGlobalAddressELFSmall(Op, DAG);
2046 case CodeModel::Large:
2047 return LowerGlobalAddressELFLarge(Op, DAG);
2049 llvm_unreachable("Only small and large code models supported now");
2053 SDValue AArch64TargetLowering::LowerTLSDescCall(SDValue SymAddr,
2056 SelectionDAG &DAG) const {
2057 EVT PtrVT = getPointerTy();
2059 // The function we need to call is simply the first entry in the GOT for this
2060 // descriptor, load it in preparation.
2061 SDValue Func, Chain;
2062 Func = DAG.getNode(AArch64ISD::GOTLoad, DL, PtrVT, DAG.getEntryNode(),
2065 // The function takes only one argument: the address of the descriptor itself
2068 Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::X0, DescAddr, Glue);
2069 Glue = Chain.getValue(1);
2071 // Finally, there's a special calling-convention which means that the lookup
2072 // must preserve all registers (except X0, obviously).
2073 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2074 const AArch64RegisterInfo *A64RI
2075 = static_cast<const AArch64RegisterInfo *>(TRI);
2076 const uint32_t *Mask = A64RI->getTLSDescCallPreservedMask();
2078 // We're now ready to populate the argument list, as with a normal call:
2079 std::vector<SDValue> Ops;
2080 Ops.push_back(Chain);
2081 Ops.push_back(Func);
2082 Ops.push_back(SymAddr);
2083 Ops.push_back(DAG.getRegister(AArch64::X0, PtrVT));
2084 Ops.push_back(DAG.getRegisterMask(Mask));
2085 Ops.push_back(Glue);
2087 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2088 Chain = DAG.getNode(AArch64ISD::TLSDESCCALL, DL, NodeTys, &Ops[0],
2090 Glue = Chain.getValue(1);
2092 // After the call, the offset from TPIDR_EL0 is in X0, copy it out and pass it
2093 // back to the generic handling code.
2094 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
2098 AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2099 SelectionDAG &DAG) const {
2100 assert(getSubtarget()->isTargetELF() &&
2101 "TLS not implemented for non-ELF targets");
2102 assert(getTargetMachine().getCodeModel() == CodeModel::Small
2103 && "TLS only supported in small memory model");
2104 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2106 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2109 EVT PtrVT = getPointerTy();
2111 const GlobalValue *GV = GA->getGlobal();
2113 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
2115 if (Model == TLSModel::InitialExec) {
2116 TPOff = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2117 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2118 AArch64II::MO_GOTTPREL),
2119 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2120 AArch64II::MO_GOTTPREL_LO12),
2121 DAG.getConstant(8, MVT::i32));
2122 TPOff = DAG.getNode(AArch64ISD::GOTLoad, DL, PtrVT, DAG.getEntryNode(),
2124 } else if (Model == TLSModel::LocalExec) {
2125 SDValue HiVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2126 AArch64II::MO_TPREL_G1);
2127 SDValue LoVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2128 AArch64II::MO_TPREL_G0_NC);
2130 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZxii, DL, PtrVT, HiVar,
2131 DAG.getTargetConstant(1, MVT::i32)), 0);
2132 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKxii, DL, PtrVT,
2134 DAG.getTargetConstant(0, MVT::i32)), 0);
2135 } else if (Model == TLSModel::GeneralDynamic) {
2136 // Accesses used in this sequence go via the TLS descriptor which lives in
2137 // the GOT. Prepare an address we can use to handle this.
2138 SDValue HiDesc = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2139 AArch64II::MO_TLSDESC);
2140 SDValue LoDesc = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2141 AArch64II::MO_TLSDESC_LO12);
2142 SDValue DescAddr = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2144 DAG.getConstant(8, MVT::i32));
2145 SDValue SymAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0);
2147 TPOff = LowerTLSDescCall(SymAddr, DescAddr, DL, DAG);
2148 } else if (Model == TLSModel::LocalDynamic) {
2149 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2150 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2151 // the beginning of the module's TLS region, followed by a DTPREL offset
2154 // These accesses will need deduplicating if there's more than one.
2155 AArch64MachineFunctionInfo* MFI = DAG.getMachineFunction()
2156 .getInfo<AArch64MachineFunctionInfo>();
2157 MFI->incNumLocalDynamicTLSAccesses();
2160 // Get the location of _TLS_MODULE_BASE_:
2161 SDValue HiDesc = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2162 AArch64II::MO_TLSDESC);
2163 SDValue LoDesc = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2164 AArch64II::MO_TLSDESC_LO12);
2165 SDValue DescAddr = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2167 DAG.getConstant(8, MVT::i32));
2168 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT);
2170 ThreadBase = LowerTLSDescCall(SymAddr, DescAddr, DL, DAG);
2172 // Get the variable's offset from _TLS_MODULE_BASE_
2173 SDValue HiVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2174 AArch64II::MO_DTPREL_G1);
2175 SDValue LoVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2176 AArch64II::MO_DTPREL_G0_NC);
2178 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZxii, DL, PtrVT, HiVar,
2179 DAG.getTargetConstant(0, MVT::i32)), 0);
2180 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKxii, DL, PtrVT,
2182 DAG.getTargetConstant(0, MVT::i32)), 0);
2184 llvm_unreachable("Unsupported TLS access model");
2187 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2191 AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG,
2192 bool IsSigned) const {
2193 if (Op.getValueType() != MVT::f128) {
2194 // Legal for everything except f128.
2200 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2202 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2204 return LowerF128ToCall(Op, DAG, LC);
2209 AArch64TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2210 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2212 EVT PtrVT = getPointerTy();
2214 // When compiling PIC, jump tables get put in the code section so a static
2215 // relocation-style is acceptable for both cases.
2216 switch (getTargetMachine().getCodeModel()) {
2217 case CodeModel::Small:
2218 return DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2219 DAG.getTargetJumpTable(JT->getIndex(), PtrVT),
2220 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2221 AArch64II::MO_LO12),
2222 DAG.getConstant(1, MVT::i32));
2223 case CodeModel::Large:
2225 AArch64ISD::WrapperLarge, dl, PtrVT,
2226 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G3),
2227 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G2_NC),
2228 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G1_NC),
2229 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G0_NC));
2231 llvm_unreachable("Only small and large code models supported now");
2235 // (SELECT_CC lhs, rhs, iftrue, iffalse, condcode)
2237 AArch64TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2239 SDValue LHS = Op.getOperand(0);
2240 SDValue RHS = Op.getOperand(1);
2241 SDValue IfTrue = Op.getOperand(2);
2242 SDValue IfFalse = Op.getOperand(3);
2243 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2245 if (LHS.getValueType() == MVT::f128) {
2246 // f128 comparisons are lowered to libcalls, but slot in nicely here
2248 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2250 // If softenSetCCOperands returned a scalar, we need to compare the result
2251 // against zero to select between true and false values.
2252 if (RHS.getNode() == 0) {
2253 RHS = DAG.getConstant(0, LHS.getValueType());
2258 if (LHS.getValueType().isInteger()) {
2261 // Integers are handled in a separate function because the combinations of
2262 // immediates and tests can get hairy and we may want to fiddle things.
2263 SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
2265 return DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2266 CmpOp, IfTrue, IfFalse, A64cc);
2269 // Note that some LLVM floating-point CondCodes can't be lowered to a single
2270 // conditional branch, hence FPCCToA64CC can set a second test, where either
2271 // passing is sufficient.
2272 A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
2273 CondCode = FPCCToA64CC(CC, Alternative);
2274 SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
2275 SDValue SetCC = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
2276 DAG.getCondCode(CC));
2277 SDValue A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl,
2279 SetCC, IfTrue, IfFalse, A64cc);
2281 if (Alternative != A64CC::Invalid) {
2282 A64cc = DAG.getConstant(Alternative, MVT::i32);
2283 A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2284 SetCC, IfTrue, A64SELECT_CC, A64cc);
2288 return A64SELECT_CC;
2291 // (SELECT testbit, iftrue, iffalse)
2293 AArch64TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2295 SDValue TheBit = Op.getOperand(0);
2296 SDValue IfTrue = Op.getOperand(1);
2297 SDValue IfFalse = Op.getOperand(2);
2299 // AArch64 BooleanContents is the default UndefinedBooleanContent, which means
2300 // that as the consumer we are responsible for ignoring rubbish in higher
2302 TheBit = DAG.getNode(ISD::AND, dl, MVT::i32, TheBit,
2303 DAG.getConstant(1, MVT::i32));
2304 SDValue A64CMP = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, TheBit,
2305 DAG.getConstant(0, TheBit.getValueType()),
2306 DAG.getCondCode(ISD::SETNE));
2308 return DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2309 A64CMP, IfTrue, IfFalse,
2310 DAG.getConstant(A64CC::NE, MVT::i32));
2313 static SDValue LowerVectorSETCC(SDValue Op, SelectionDAG &DAG) {
2315 SDValue LHS = Op.getOperand(0);
2316 SDValue RHS = Op.getOperand(1);
2317 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2318 EVT VT = Op.getValueType();
2319 bool Invert = false;
2323 if (LHS.getValueType().isInteger()) {
2325 // Attempt to use Vector Integer Compare Mask Test instruction.
2326 // TST = icmp ne (and (op0, op1), zero).
2327 if (CC == ISD::SETNE) {
2328 if (((LHS.getOpcode() == ISD::AND) &&
2329 ISD::isBuildVectorAllZeros(RHS.getNode())) ||
2330 ((RHS.getOpcode() == ISD::AND) &&
2331 ISD::isBuildVectorAllZeros(LHS.getNode()))) {
2333 SDValue AndOp = (LHS.getOpcode() == ISD::AND) ? LHS : RHS;
2334 SDValue NewLHS = DAG.getNode(ISD::BITCAST, DL, VT, AndOp.getOperand(0));
2335 SDValue NewRHS = DAG.getNode(ISD::BITCAST, DL, VT, AndOp.getOperand(1));
2336 return DAG.getNode(AArch64ISD::NEON_TST, DL, VT, NewLHS, NewRHS);
2340 // Attempt to use Vector Integer Compare Mask against Zero instr (Signed).
2341 // Note: Compare against Zero does not support unsigned predicates.
2342 if ((ISD::isBuildVectorAllZeros(RHS.getNode()) ||
2343 ISD::isBuildVectorAllZeros(LHS.getNode())) &&
2344 !isUnsignedIntSetCC(CC)) {
2346 // If LHS is the zero value, swap operands and CondCode.
2347 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
2348 CC = getSetCCSwappedOperands(CC);
2353 // Ensure valid CondCode for Compare Mask against Zero instruction:
2354 // EQ, GE, GT, LE, LT.
2355 if (ISD::SETNE == CC) {
2360 // Using constant type to differentiate integer and FP compares with zero.
2361 Op1 = DAG.getConstant(0, MVT::i32);
2362 Opcode = AArch64ISD::NEON_CMPZ;
2365 // Attempt to use Vector Integer Compare Mask instr (Signed/Unsigned).
2366 // Ensure valid CondCode for Compare Mask instr: EQ, GE, GT, UGE, UGT.
2370 llvm_unreachable("Illegal integer comparison.");
2386 CC = getSetCCSwappedOperands(CC);
2390 std::swap(LHS, RHS);
2392 Opcode = AArch64ISD::NEON_CMP;
2397 // Generate Compare Mask instr or Compare Mask against Zero instr.
2399 DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(CC));
2402 NeonCmp = DAG.getNOT(DL, NeonCmp, VT);
2407 // Now handle Floating Point cases.
2408 // Attempt to use Vector Floating Point Compare Mask against Zero instruction.
2409 if (ISD::isBuildVectorAllZeros(RHS.getNode()) ||
2410 ISD::isBuildVectorAllZeros(LHS.getNode())) {
2412 // If LHS is the zero value, swap operands and CondCode.
2413 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
2414 CC = getSetCCSwappedOperands(CC);
2419 // Using constant type to differentiate integer and FP compares with zero.
2420 Op1 = DAG.getConstantFP(0, MVT::f32);
2421 Opcode = AArch64ISD::NEON_CMPZ;
2423 // Attempt to use Vector Floating Point Compare Mask instruction.
2426 Opcode = AArch64ISD::NEON_CMP;
2430 // Some register compares have to be implemented with swapped CC and operands,
2431 // e.g.: OLT implemented as OGT with swapped operands.
2432 bool SwapIfRegArgs = false;
2434 // Ensure valid CondCode for FP Compare Mask against Zero instruction:
2435 // EQ, GE, GT, LE, LT.
2436 // And ensure valid CondCode for FP Compare Mask instruction: EQ, GE, GT.
2439 llvm_unreachable("Illegal FP comparison");
2442 Invert = true; // Fallthrough
2450 SwapIfRegArgs = true;
2459 SwapIfRegArgs = true;
2468 SwapIfRegArgs = true;
2477 SwapIfRegArgs = true;
2484 Invert = true; // Fallthrough
2486 // Expand this to (OGT |OLT).
2488 DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(ISD::SETGT));
2490 SwapIfRegArgs = true;
2493 Invert = true; // Fallthrough
2495 // Expand this to (OGE | OLT).
2497 DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(ISD::SETGE));
2499 SwapIfRegArgs = true;
2503 if (Opcode == AArch64ISD::NEON_CMP && SwapIfRegArgs) {
2504 CC = getSetCCSwappedOperands(CC);
2505 std::swap(Op0, Op1);
2508 // Generate FP Compare Mask instr or FP Compare Mask against Zero instr
2509 SDValue NeonCmp = DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(CC));
2511 if (NeonCmpAlt.getNode())
2512 NeonCmp = DAG.getNode(ISD::OR, DL, VT, NeonCmp, NeonCmpAlt);
2515 NeonCmp = DAG.getNOT(DL, NeonCmp, VT);
2520 // (SETCC lhs, rhs, condcode)
2522 AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2524 SDValue LHS = Op.getOperand(0);
2525 SDValue RHS = Op.getOperand(1);
2526 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2527 EVT VT = Op.getValueType();
2530 return LowerVectorSETCC(Op, DAG);
2532 if (LHS.getValueType() == MVT::f128) {
2533 // f128 comparisons will be lowered to libcalls giving a valid LHS and RHS
2534 // for the rest of the function (some i32 or i64 values).
2535 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2537 // If softenSetCCOperands returned a scalar, use it.
2538 if (RHS.getNode() == 0) {
2539 assert(LHS.getValueType() == Op.getValueType() &&
2540 "Unexpected setcc expansion!");
2545 if (LHS.getValueType().isInteger()) {
2548 // Integers are handled in a separate function because the combinations of
2549 // immediates and tests can get hairy and we may want to fiddle things.
2550 SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
2552 return DAG.getNode(AArch64ISD::SELECT_CC, dl, VT,
2553 CmpOp, DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2557 // Note that some LLVM floating-point CondCodes can't be lowered to a single
2558 // conditional branch, hence FPCCToA64CC can set a second test, where either
2559 // passing is sufficient.
2560 A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
2561 CondCode = FPCCToA64CC(CC, Alternative);
2562 SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
2563 SDValue CmpOp = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
2564 DAG.getCondCode(CC));
2565 SDValue A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT,
2566 CmpOp, DAG.getConstant(1, VT),
2567 DAG.getConstant(0, VT), A64cc);
2569 if (Alternative != A64CC::Invalid) {
2570 A64cc = DAG.getConstant(Alternative, MVT::i32);
2571 A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT, CmpOp,
2572 DAG.getConstant(1, VT), A64SELECT_CC, A64cc);
2575 return A64SELECT_CC;
2579 AArch64TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2580 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2581 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2583 // We have to make sure we copy the entire structure: 8+8+8+4+4 = 32 bytes
2584 // rather than just 8.
2585 return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op),
2586 Op.getOperand(1), Op.getOperand(2),
2587 DAG.getConstant(32, MVT::i32), 8, false, false,
2588 MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
2592 AArch64TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2593 // The layout of the va_list struct is specified in the AArch64 Procedure Call
2594 // Standard, section B.3.
2595 MachineFunction &MF = DAG.getMachineFunction();
2596 AArch64MachineFunctionInfo *FuncInfo
2597 = MF.getInfo<AArch64MachineFunctionInfo>();
2600 SDValue Chain = Op.getOperand(0);
2601 SDValue VAList = Op.getOperand(1);
2602 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2603 SmallVector<SDValue, 4> MemOps;
2605 // void *__stack at offset 0
2606 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVariadicStackIdx(),
2608 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
2609 MachinePointerInfo(SV), false, false, 0));
2611 // void *__gr_top at offset 8
2612 int GPRSize = FuncInfo->getVariadicGPRSize();
2614 SDValue GRTop, GRTopAddr;
2616 GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2617 DAG.getConstant(8, getPointerTy()));
2619 GRTop = DAG.getFrameIndex(FuncInfo->getVariadicGPRIdx(), getPointerTy());
2620 GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
2621 DAG.getConstant(GPRSize, getPointerTy()));
2623 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
2624 MachinePointerInfo(SV, 8),
2628 // void *__vr_top at offset 16
2629 int FPRSize = FuncInfo->getVariadicFPRSize();
2631 SDValue VRTop, VRTopAddr;
2632 VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2633 DAG.getConstant(16, getPointerTy()));
2635 VRTop = DAG.getFrameIndex(FuncInfo->getVariadicFPRIdx(), getPointerTy());
2636 VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
2637 DAG.getConstant(FPRSize, getPointerTy()));
2639 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
2640 MachinePointerInfo(SV, 16),
2644 // int __gr_offs at offset 24
2645 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2646 DAG.getConstant(24, getPointerTy()));
2647 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
2648 GROffsAddr, MachinePointerInfo(SV, 24),
2651 // int __vr_offs at offset 28
2652 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2653 DAG.getConstant(28, getPointerTy()));
2654 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
2655 VROffsAddr, MachinePointerInfo(SV, 28),
2658 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
2663 AArch64TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
2664 switch (Op.getOpcode()) {
2665 default: llvm_unreachable("Don't know how to custom lower this!");
2666 case ISD::FADD: return LowerF128ToCall(Op, DAG, RTLIB::ADD_F128);
2667 case ISD::FSUB: return LowerF128ToCall(Op, DAG, RTLIB::SUB_F128);
2668 case ISD::FMUL: return LowerF128ToCall(Op, DAG, RTLIB::MUL_F128);
2669 case ISD::FDIV: return LowerF128ToCall(Op, DAG, RTLIB::DIV_F128);
2670 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, true);
2671 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG, false);
2672 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG, true);
2673 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG, false);
2674 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
2675 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
2677 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
2678 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
2679 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
2680 case ISD::GlobalAddress: return LowerGlobalAddressELF(Op, DAG);
2681 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
2682 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
2683 case ISD::SELECT: return LowerSELECT(Op, DAG);
2684 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
2685 case ISD::SETCC: return LowerSETCC(Op, DAG);
2686 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
2687 case ISD::VASTART: return LowerVASTART(Op, DAG);
2688 case ISD::BUILD_VECTOR:
2689 return LowerBUILD_VECTOR(Op, DAG, getSubtarget());
2695 /// Check if the specified splat value corresponds to a valid vector constant
2696 /// for a Neon instruction with a "modified immediate" operand (e.g., MOVI). If
2697 /// so, return the encoded 8-bit immediate and the OpCmode instruction fields
2699 static bool isNeonModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
2700 unsigned SplatBitSize, SelectionDAG &DAG,
2701 bool is128Bits, NeonModImmType type, EVT &VT,
2702 unsigned &Imm, unsigned &OpCmode) {
2703 switch (SplatBitSize) {
2705 llvm_unreachable("unexpected size for isNeonModifiedImm");
2707 if (type != Neon_Mov_Imm)
2709 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
2710 // Neon movi per byte: Op=0, Cmode=1110.
2713 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
2717 // Neon move inst per halfword
2718 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
2719 if ((SplatBits & ~0xff) == 0) {
2720 // Value = 0x00nn is 0x00nn LSL 0
2721 // movi: Op=0, Cmode=1000; mvni: Op=1, Cmode=1000
2722 // bic: Op=1, Cmode=1001; orr: Op=0, Cmode=1001
2728 if ((SplatBits & ~0xff00) == 0) {
2729 // Value = 0xnn00 is 0x00nn LSL 8
2730 // movi: Op=0, Cmode=1010; mvni: Op=1, Cmode=1010
2731 // bic: Op=1, Cmode=1011; orr: Op=0, Cmode=1011
2733 Imm = SplatBits >> 8;
2737 // can't handle any other
2742 // First the LSL variants (MSL is unusable by some interested instructions).
2744 // Neon move instr per word, shift zeros
2745 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
2746 if ((SplatBits & ~0xff) == 0) {
2747 // Value = 0x000000nn is 0x000000nn LSL 0
2748 // movi: Op=0, Cmode= 0000; mvni: Op=1, Cmode= 0000
2749 // bic: Op=1, Cmode= 0001; orr: Op=0, Cmode= 0001
2755 if ((SplatBits & ~0xff00) == 0) {
2756 // Value = 0x0000nn00 is 0x000000nn LSL 8
2757 // movi: Op=0, Cmode= 0010; mvni: Op=1, Cmode= 0010
2758 // bic: Op=1, Cmode= 0011; orr : Op=0, Cmode= 0011
2760 Imm = SplatBits >> 8;
2764 if ((SplatBits & ~0xff0000) == 0) {
2765 // Value = 0x00nn0000 is 0x000000nn LSL 16
2766 // movi: Op=0, Cmode= 0100; mvni: Op=1, Cmode= 0100
2767 // bic: Op=1, Cmode= 0101; orr: Op=0, Cmode= 0101
2769 Imm = SplatBits >> 16;
2773 if ((SplatBits & ~0xff000000) == 0) {
2774 // Value = 0xnn000000 is 0x000000nn LSL 24
2775 // movi: Op=0, Cmode= 0110; mvni: Op=1, Cmode= 0110
2776 // bic: Op=1, Cmode= 0111; orr: Op=0, Cmode= 0111
2778 Imm = SplatBits >> 24;
2783 // Now the MSL immediates.
2785 // Neon move instr per word, shift ones
2786 if ((SplatBits & ~0xffff) == 0 &&
2787 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
2788 // Value = 0x0000nnff is 0x000000nn MSL 8
2789 // movi: Op=0, Cmode= 1100; mvni: Op=1, Cmode= 1100
2791 Imm = SplatBits >> 8;
2795 if ((SplatBits & ~0xffffff) == 0 &&
2796 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
2797 // Value = 0x00nnffff is 0x000000nn MSL 16
2798 // movi: Op=1, Cmode= 1101; mvni: Op=1, Cmode= 1101
2800 Imm = SplatBits >> 16;
2804 // can't handle any other
2809 if (type != Neon_Mov_Imm)
2811 // Neon move instr bytemask, where each byte is either 0x00 or 0xff.
2812 // movi Op=1, Cmode=1110.
2814 uint64_t BitMask = 0xff;
2816 unsigned ImmMask = 1;
2818 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
2819 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
2822 } else if ((SplatBits & BitMask) != 0) {
2829 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
2837 static SDValue PerformANDCombine(SDNode *N,
2838 TargetLowering::DAGCombinerInfo &DCI) {
2840 SelectionDAG &DAG = DCI.DAG;
2842 EVT VT = N->getValueType(0);
2844 // We're looking for an SRA/SHL pair which form an SBFX.
2846 if (VT != MVT::i32 && VT != MVT::i64)
2849 if (!isa<ConstantSDNode>(N->getOperand(1)))
2852 uint64_t TruncMask = N->getConstantOperandVal(1);
2853 if (!isMask_64(TruncMask))
2856 uint64_t Width = CountPopulation_64(TruncMask);
2857 SDValue Shift = N->getOperand(0);
2859 if (Shift.getOpcode() != ISD::SRL)
2862 if (!isa<ConstantSDNode>(Shift->getOperand(1)))
2864 uint64_t LSB = Shift->getConstantOperandVal(1);
2866 if (LSB > VT.getSizeInBits() || Width > VT.getSizeInBits())
2869 return DAG.getNode(AArch64ISD::UBFX, DL, VT, Shift.getOperand(0),
2870 DAG.getConstant(LSB, MVT::i64),
2871 DAG.getConstant(LSB + Width - 1, MVT::i64));
2874 /// For a true bitfield insert, the bits getting into that contiguous mask
2875 /// should come from the low part of an existing value: they must be formed from
2876 /// a compatible SHL operation (unless they're already low). This function
2877 /// checks that condition and returns the least-significant bit that's
2878 /// intended. If the operation not a field preparation, -1 is returned.
2879 static int32_t getLSBForBFI(SelectionDAG &DAG, SDLoc DL, EVT VT,
2880 SDValue &MaskedVal, uint64_t Mask) {
2881 if (!isShiftedMask_64(Mask))
2884 // Now we need to alter MaskedVal so that it is an appropriate input for a BFI
2885 // instruction. BFI will do a left-shift by LSB before applying the mask we've
2886 // spotted, so in general we should pre-emptively "undo" that by making sure
2887 // the incoming bits have had a right-shift applied to them.
2889 // This right shift, however, will combine with existing left/right shifts. In
2890 // the simplest case of a completely straight bitfield operation, it will be
2891 // expected to completely cancel out with an existing SHL. More complicated
2892 // cases (e.g. bitfield to bitfield copy) may still need a real shift before
2895 uint64_t LSB = countTrailingZeros(Mask);
2896 int64_t ShiftRightRequired = LSB;
2897 if (MaskedVal.getOpcode() == ISD::SHL &&
2898 isa<ConstantSDNode>(MaskedVal.getOperand(1))) {
2899 ShiftRightRequired -= MaskedVal.getConstantOperandVal(1);
2900 MaskedVal = MaskedVal.getOperand(0);
2901 } else if (MaskedVal.getOpcode() == ISD::SRL &&
2902 isa<ConstantSDNode>(MaskedVal.getOperand(1))) {
2903 ShiftRightRequired += MaskedVal.getConstantOperandVal(1);
2904 MaskedVal = MaskedVal.getOperand(0);
2907 if (ShiftRightRequired > 0)
2908 MaskedVal = DAG.getNode(ISD::SRL, DL, VT, MaskedVal,
2909 DAG.getConstant(ShiftRightRequired, MVT::i64));
2910 else if (ShiftRightRequired < 0) {
2911 // We could actually end up with a residual left shift, for example with
2912 // "struc.bitfield = val << 1".
2913 MaskedVal = DAG.getNode(ISD::SHL, DL, VT, MaskedVal,
2914 DAG.getConstant(-ShiftRightRequired, MVT::i64));
2920 /// Searches from N for an existing AArch64ISD::BFI node, possibly surrounded by
2921 /// a mask and an extension. Returns true if a BFI was found and provides
2922 /// information on its surroundings.
2923 static bool findMaskedBFI(SDValue N, SDValue &BFI, uint64_t &Mask,
2926 if (N.getOpcode() == ISD::ZERO_EXTEND) {
2928 N = N.getOperand(0);
2931 if (N.getOpcode() == ISD::AND && isa<ConstantSDNode>(N.getOperand(1))) {
2932 Mask = N->getConstantOperandVal(1);
2933 N = N.getOperand(0);
2935 // Mask is the whole width.
2936 Mask = -1ULL >> (64 - N.getValueType().getSizeInBits());
2939 if (N.getOpcode() == AArch64ISD::BFI) {
2947 /// Try to combine a subtree (rooted at an OR) into a "masked BFI" node, which
2948 /// is roughly equivalent to (and (BFI ...), mask). This form is used because it
2949 /// can often be further combined with a larger mask. Ultimately, we want mask
2950 /// to be 2^32-1 or 2^64-1 so the AND can be skipped.
2951 static SDValue tryCombineToBFI(SDNode *N,
2952 TargetLowering::DAGCombinerInfo &DCI,
2953 const AArch64Subtarget *Subtarget) {
2954 SelectionDAG &DAG = DCI.DAG;
2956 EVT VT = N->getValueType(0);
2958 assert(N->getOpcode() == ISD::OR && "Unexpected root");
2960 // We need the LHS to be (and SOMETHING, MASK). Find out what that mask is or
2961 // abandon the effort.
2962 SDValue LHS = N->getOperand(0);
2963 if (LHS.getOpcode() != ISD::AND)
2967 if (isa<ConstantSDNode>(LHS.getOperand(1)))
2968 LHSMask = LHS->getConstantOperandVal(1);
2972 // We also need the RHS to be (and SOMETHING, MASK). Find out what that mask
2973 // is or abandon the effort.
2974 SDValue RHS = N->getOperand(1);
2975 if (RHS.getOpcode() != ISD::AND)
2979 if (isa<ConstantSDNode>(RHS.getOperand(1)))
2980 RHSMask = RHS->getConstantOperandVal(1);
2984 // Can't do anything if the masks are incompatible.
2985 if (LHSMask & RHSMask)
2988 // Now we need one of the masks to be a contiguous field. Without loss of
2989 // generality that should be the RHS one.
2990 SDValue Bitfield = LHS.getOperand(0);
2991 if (getLSBForBFI(DAG, DL, VT, Bitfield, LHSMask) != -1) {
2992 // We know that LHS is a candidate new value, and RHS isn't already a better
2994 std::swap(LHS, RHS);
2995 std::swap(LHSMask, RHSMask);
2998 // We've done our best to put the right operands in the right places, all we
2999 // can do now is check whether a BFI exists.
3000 Bitfield = RHS.getOperand(0);
3001 int32_t LSB = getLSBForBFI(DAG, DL, VT, Bitfield, RHSMask);
3005 uint32_t Width = CountPopulation_64(RHSMask);
3006 assert(Width && "Expected non-zero bitfield width");
3008 SDValue BFI = DAG.getNode(AArch64ISD::BFI, DL, VT,
3009 LHS.getOperand(0), Bitfield,
3010 DAG.getConstant(LSB, MVT::i64),
3011 DAG.getConstant(Width, MVT::i64));
3014 if ((LHSMask | RHSMask) == (-1ULL >> (64 - VT.getSizeInBits())))
3017 return DAG.getNode(ISD::AND, DL, VT, BFI,
3018 DAG.getConstant(LHSMask | RHSMask, VT));
3021 /// Search for the bitwise combining (with careful masks) of a MaskedBFI and its
3022 /// original input. This is surprisingly common because SROA splits things up
3023 /// into i8 chunks, so the originally detected MaskedBFI may actually only act
3024 /// on the low (say) byte of a word. This is then orred into the rest of the
3025 /// word afterwards.
3027 /// Basic input: (or (and OLDFIELD, MASK1), (MaskedBFI MASK2, OLDFIELD, ...)).
3029 /// If MASK1 and MASK2 are compatible, we can fold the whole thing into the
3030 /// MaskedBFI. We can also deal with a certain amount of extend/truncate being
3032 static SDValue tryCombineToLargerBFI(SDNode *N,
3033 TargetLowering::DAGCombinerInfo &DCI,
3034 const AArch64Subtarget *Subtarget) {
3035 SelectionDAG &DAG = DCI.DAG;
3037 EVT VT = N->getValueType(0);
3039 // First job is to hunt for a MaskedBFI on either the left or right. Swap
3040 // operands if it's actually on the right.
3042 SDValue PossExtraMask;
3043 uint64_t ExistingMask = 0;
3044 bool Extended = false;
3045 if (findMaskedBFI(N->getOperand(0), BFI, ExistingMask, Extended))
3046 PossExtraMask = N->getOperand(1);
3047 else if (findMaskedBFI(N->getOperand(1), BFI, ExistingMask, Extended))
3048 PossExtraMask = N->getOperand(0);
3052 // We can only combine a BFI with another compatible mask.
3053 if (PossExtraMask.getOpcode() != ISD::AND ||
3054 !isa<ConstantSDNode>(PossExtraMask.getOperand(1)))
3057 uint64_t ExtraMask = PossExtraMask->getConstantOperandVal(1);
3059 // Masks must be compatible.
3060 if (ExtraMask & ExistingMask)
3063 SDValue OldBFIVal = BFI.getOperand(0);
3064 SDValue NewBFIVal = BFI.getOperand(1);
3066 // We skipped a ZERO_EXTEND above, so the input to the MaskedBFIs should be
3067 // 32-bit and we'll be forming a 64-bit MaskedBFI. The MaskedBFI arguments
3068 // need to be made compatible.
3069 assert(VT == MVT::i64 && BFI.getValueType() == MVT::i32
3070 && "Invalid types for BFI");
3071 OldBFIVal = DAG.getNode(ISD::ANY_EXTEND, DL, VT, OldBFIVal);
3072 NewBFIVal = DAG.getNode(ISD::ANY_EXTEND, DL, VT, NewBFIVal);
3075 // We need the MaskedBFI to be combined with a mask of the *same* value.
3076 if (PossExtraMask.getOperand(0) != OldBFIVal)
3079 BFI = DAG.getNode(AArch64ISD::BFI, DL, VT,
3080 OldBFIVal, NewBFIVal,
3081 BFI.getOperand(2), BFI.getOperand(3));
3083 // If the masking is trivial, we don't need to create it.
3084 if ((ExtraMask | ExistingMask) == (-1ULL >> (64 - VT.getSizeInBits())))
3087 return DAG.getNode(ISD::AND, DL, VT, BFI,
3088 DAG.getConstant(ExtraMask | ExistingMask, VT));
3091 /// An EXTR instruction is made up of two shifts, ORed together. This helper
3092 /// searches for and classifies those shifts.
3093 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
3095 if (N.getOpcode() == ISD::SHL)
3097 else if (N.getOpcode() == ISD::SRL)
3102 if (!isa<ConstantSDNode>(N.getOperand(1)))
3105 ShiftAmount = N->getConstantOperandVal(1);
3106 Src = N->getOperand(0);
3110 /// EXTR instruction extracts a contiguous chunk of bits from two existing
3111 /// registers viewed as a high/low pair. This function looks for the pattern:
3112 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
3113 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
3115 static SDValue tryCombineToEXTR(SDNode *N,
3116 TargetLowering::DAGCombinerInfo &DCI) {
3117 SelectionDAG &DAG = DCI.DAG;
3119 EVT VT = N->getValueType(0);
3121 assert(N->getOpcode() == ISD::OR && "Unexpected root");
3123 if (VT != MVT::i32 && VT != MVT::i64)
3127 uint32_t ShiftLHS = 0;
3129 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
3133 uint32_t ShiftRHS = 0;
3135 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
3138 // If they're both trying to come from the high part of the register, they're
3139 // not really an EXTR.
3140 if (LHSFromHi == RHSFromHi)
3143 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
3147 std::swap(LHS, RHS);
3148 std::swap(ShiftLHS, ShiftRHS);
3151 return DAG.getNode(AArch64ISD::EXTR, DL, VT,
3153 DAG.getConstant(ShiftRHS, MVT::i64));
3156 /// Target-specific dag combine xforms for ISD::OR
3157 static SDValue PerformORCombine(SDNode *N,
3158 TargetLowering::DAGCombinerInfo &DCI,
3159 const AArch64Subtarget *Subtarget) {
3161 SelectionDAG &DAG = DCI.DAG;
3163 EVT VT = N->getValueType(0);
3165 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
3168 // Attempt to recognise bitfield-insert operations.
3169 SDValue Res = tryCombineToBFI(N, DCI, Subtarget);
3173 // Attempt to combine an existing MaskedBFI operation into one with a larger
3175 Res = tryCombineToLargerBFI(N, DCI, Subtarget);
3179 Res = tryCombineToEXTR(N, DCI);
3183 if (!Subtarget->hasNEON())
3186 // Attempt to use vector immediate-form BSL
3187 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
3189 SDValue N0 = N->getOperand(0);
3190 if (N0.getOpcode() != ISD::AND)
3193 SDValue N1 = N->getOperand(1);
3194 if (N1.getOpcode() != ISD::AND)
3197 if (VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
3199 unsigned SplatBitSize;
3201 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
3203 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
3206 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
3208 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
3210 !HasAnyUndefs && SplatBits0 == ~SplatBits1) {
3211 // Canonicalize the vector type to make instruction selection simpler.
3212 EVT CanonicalVT = VT.is128BitVector() ? MVT::v16i8 : MVT::v8i8;
3213 SDValue Result = DAG.getNode(AArch64ISD::NEON_BSL, DL, CanonicalVT,
3214 N0->getOperand(1), N0->getOperand(0),
3216 return DAG.getNode(ISD::BITCAST, DL, VT, Result);
3224 /// Target-specific dag combine xforms for ISD::SRA
3225 static SDValue PerformSRACombine(SDNode *N,
3226 TargetLowering::DAGCombinerInfo &DCI) {
3228 SelectionDAG &DAG = DCI.DAG;
3230 EVT VT = N->getValueType(0);
3232 // We're looking for an SRA/SHL pair which form an SBFX.
3234 if (VT != MVT::i32 && VT != MVT::i64)
3237 if (!isa<ConstantSDNode>(N->getOperand(1)))
3240 uint64_t ExtraSignBits = N->getConstantOperandVal(1);
3241 SDValue Shift = N->getOperand(0);
3243 if (Shift.getOpcode() != ISD::SHL)
3246 if (!isa<ConstantSDNode>(Shift->getOperand(1)))
3249 uint64_t BitsOnLeft = Shift->getConstantOperandVal(1);
3250 uint64_t Width = VT.getSizeInBits() - ExtraSignBits;
3251 uint64_t LSB = VT.getSizeInBits() - Width - BitsOnLeft;
3253 if (LSB > VT.getSizeInBits() || Width > VT.getSizeInBits())
3256 return DAG.getNode(AArch64ISD::SBFX, DL, VT, Shift.getOperand(0),
3257 DAG.getConstant(LSB, MVT::i64),
3258 DAG.getConstant(LSB + Width - 1, MVT::i64));
3261 /// Check if this is a valid build_vector for the immediate operand of
3262 /// a vector shift operation, where all the elements of the build_vector
3263 /// must have the same constant integer value.
3264 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
3265 // Ignore bit_converts.
3266 while (Op.getOpcode() == ISD::BITCAST)
3267 Op = Op.getOperand(0);
3268 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
3269 APInt SplatBits, SplatUndef;
3270 unsigned SplatBitSize;
3272 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
3273 HasAnyUndefs, ElementBits) ||
3274 SplatBitSize > ElementBits)
3276 Cnt = SplatBits.getSExtValue();
3280 /// Check if this is a valid build_vector for the immediate operand of
3281 /// a vector shift left operation. That value must be in the range:
3282 /// 0 <= Value < ElementBits
3283 static bool isVShiftLImm(SDValue Op, EVT VT, int64_t &Cnt) {
3284 assert(VT.isVector() && "vector shift count is not a vector type");
3285 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3286 if (!getVShiftImm(Op, ElementBits, Cnt))
3288 return (Cnt >= 0 && Cnt < ElementBits);
3291 /// Check if this is a valid build_vector for the immediate operand of a
3292 /// vector shift right operation. The value must be in the range:
3293 /// 1 <= Value <= ElementBits
3294 static bool isVShiftRImm(SDValue Op, EVT VT, int64_t &Cnt) {
3295 assert(VT.isVector() && "vector shift count is not a vector type");
3296 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3297 if (!getVShiftImm(Op, ElementBits, Cnt))
3299 return (Cnt >= 1 && Cnt <= ElementBits);
3302 /// Checks for immediate versions of vector shifts and lowers them.
3303 static SDValue PerformShiftCombine(SDNode *N,
3304 TargetLowering::DAGCombinerInfo &DCI,
3305 const AArch64Subtarget *ST) {
3306 SelectionDAG &DAG = DCI.DAG;
3307 EVT VT = N->getValueType(0);
3308 if (N->getOpcode() == ISD::SRA && (VT == MVT::i32 || VT == MVT::i64))
3309 return PerformSRACombine(N, DCI);
3311 // Nothing to be done for scalar shifts.
3312 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3313 if (!VT.isVector() || !TLI.isTypeLegal(VT))
3316 assert(ST->hasNEON() && "unexpected vector shift");
3319 switch (N->getOpcode()) {
3321 llvm_unreachable("unexpected shift opcode");
3324 if (isVShiftLImm(N->getOperand(1), VT, Cnt)) {
3326 DAG.getNode(AArch64ISD::NEON_DUPIMM, SDLoc(N->getOperand(1)), VT,
3327 DAG.getConstant(Cnt, MVT::i32));
3328 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0), RHS);
3334 if (isVShiftRImm(N->getOperand(1), VT, Cnt)) {
3336 DAG.getNode(AArch64ISD::NEON_DUPIMM, SDLoc(N->getOperand(1)), VT,
3337 DAG.getConstant(Cnt, MVT::i32));
3338 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N->getOperand(0), RHS);
3346 /// ARM-specific DAG combining for intrinsics.
3347 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
3348 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3352 // Don't do anything for most intrinsics.
3355 case Intrinsic::arm_neon_vqshifts:
3356 case Intrinsic::arm_neon_vqshiftu:
3357 EVT VT = N->getOperand(1).getValueType();
3359 if (!isVShiftLImm(N->getOperand(2), VT, Cnt))
3361 unsigned VShiftOpc = (IntNo == Intrinsic::arm_neon_vqshifts)
3362 ? AArch64ISD::NEON_QSHLs
3363 : AArch64ISD::NEON_QSHLu;
3364 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
3365 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
3372 AArch64TargetLowering::PerformDAGCombine(SDNode *N,
3373 DAGCombinerInfo &DCI) const {
3374 switch (N->getOpcode()) {
3376 case ISD::AND: return PerformANDCombine(N, DCI);
3377 case ISD::OR: return PerformORCombine(N, DCI, getSubtarget());
3381 return PerformShiftCombine(N, DCI, getSubtarget());
3382 case ISD::INTRINSIC_WO_CHAIN:
3383 return PerformIntrinsicCombine(N, DCI.DAG);
3389 AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3390 VT = VT.getScalarType();
3395 switch (VT.getSimpleVT().SimpleTy) {
3409 // If this is a case we can't handle, return null and let the default
3410 // expansion code take care of it.
3412 AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
3413 const AArch64Subtarget *ST) const {
3415 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
3417 EVT VT = Op.getValueType();
3419 APInt SplatBits, SplatUndef;
3420 unsigned SplatBitSize;
3423 // Note we favor lowering MOVI over MVNI.
3424 // This has implications on the definition of patterns in TableGen to select
3425 // BIC immediate instructions but not ORR immediate instructions.
3426 // If this lowering order is changed, TableGen patterns for BIC immediate and
3427 // ORR immediate instructions have to be updated.
3428 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
3429 if (SplatBitSize <= 64) {
3430 // First attempt to use vector immediate-form MOVI
3433 unsigned OpCmode = 0;
3435 if (isNeonModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
3436 SplatBitSize, DAG, VT.is128BitVector(),
3437 Neon_Mov_Imm, NeonMovVT, Imm, OpCmode)) {
3438 SDValue ImmVal = DAG.getTargetConstant(Imm, MVT::i32);
3439 SDValue OpCmodeVal = DAG.getConstant(OpCmode, MVT::i32);
3441 if (ImmVal.getNode() && OpCmodeVal.getNode()) {
3442 SDValue NeonMov = DAG.getNode(AArch64ISD::NEON_MOVIMM, DL, NeonMovVT,
3443 ImmVal, OpCmodeVal);
3444 return DAG.getNode(ISD::BITCAST, DL, VT, NeonMov);
3448 // Then attempt to use vector immediate-form MVNI
3449 uint64_t NegatedImm = (~SplatBits).getZExtValue();
3450 if (isNeonModifiedImm(NegatedImm, SplatUndef.getZExtValue(), SplatBitSize,
3451 DAG, VT.is128BitVector(), Neon_Mvn_Imm, NeonMovVT,
3453 SDValue ImmVal = DAG.getTargetConstant(Imm, MVT::i32);
3454 SDValue OpCmodeVal = DAG.getConstant(OpCmode, MVT::i32);
3455 if (ImmVal.getNode() && OpCmodeVal.getNode()) {
3456 SDValue NeonMov = DAG.getNode(AArch64ISD::NEON_MVNIMM, DL, NeonMovVT,
3457 ImmVal, OpCmodeVal);
3458 return DAG.getNode(ISD::BITCAST, DL, VT, NeonMov);
3462 // Attempt to use vector immediate-form FMOV
3463 if (((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) ||
3464 (VT == MVT::v2f64 && SplatBitSize == 64)) {
3466 SplatBitSize == 32 ? APFloat::IEEEsingle : APFloat::IEEEdouble,
3469 if (A64Imms::isFPImm(RealVal, ImmVal)) {
3470 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
3471 return DAG.getNode(AArch64ISD::NEON_FMOVIMM, DL, VT, Val);
3479 AArch64TargetLowering::ConstraintType
3480 AArch64TargetLowering::getConstraintType(const std::string &Constraint) const {
3481 if (Constraint.size() == 1) {
3482 switch (Constraint[0]) {
3484 case 'w': // An FP/SIMD vector register
3485 return C_RegisterClass;
3486 case 'I': // Constant that can be used with an ADD instruction
3487 case 'J': // Constant that can be used with a SUB instruction
3488 case 'K': // Constant that can be used with a 32-bit logical instruction
3489 case 'L': // Constant that can be used with a 64-bit logical instruction
3490 case 'M': // Constant that can be used as a 32-bit MOV immediate
3491 case 'N': // Constant that can be used as a 64-bit MOV immediate
3492 case 'Y': // Floating point constant zero
3493 case 'Z': // Integer constant zero
3495 case 'Q': // A memory reference with base register and no offset
3497 case 'S': // A symbolic address
3502 // FIXME: Ump, Utf, Usa, Ush
3503 // Ump: A memory address suitable for ldp/stp in SI, DI, SF and DF modes,
3504 // whatever they may be
3505 // Utf: A memory address suitable for ldp/stp in TF mode, whatever it may be
3506 // Usa: An absolute symbolic address
3507 // Ush: The high part (bits 32:12) of a pc-relative symbolic address
3508 assert(Constraint != "Ump" && Constraint != "Utf" && Constraint != "Usa"
3509 && Constraint != "Ush" && "Unimplemented constraints");
3511 return TargetLowering::getConstraintType(Constraint);
3514 TargetLowering::ConstraintWeight
3515 AArch64TargetLowering::getSingleConstraintMatchWeight(AsmOperandInfo &Info,
3516 const char *Constraint) const {
3518 llvm_unreachable("Constraint weight unimplemented");
3522 AArch64TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3523 std::string &Constraint,
3524 std::vector<SDValue> &Ops,
3525 SelectionDAG &DAG) const {
3526 SDValue Result(0, 0);
3528 // Only length 1 constraints are C_Other.
3529 if (Constraint.size() != 1) return;
3531 // Only C_Other constraints get lowered like this. That means constants for us
3532 // so return early if there's no hope the constraint can be lowered.
3534 switch(Constraint[0]) {
3536 case 'I': case 'J': case 'K': case 'L':
3537 case 'M': case 'N': case 'Z': {
3538 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3542 uint64_t CVal = C->getZExtValue();
3545 switch (Constraint[0]) {
3547 // FIXME: 'M' and 'N' are MOV pseudo-insts -- unsupported in assembly. 'J'
3548 // is a peculiarly useless SUB constraint.
3549 llvm_unreachable("Unimplemented C_Other constraint");
3555 if (A64Imms::isLogicalImm(32, CVal, Bits))
3559 if (A64Imms::isLogicalImm(64, CVal, Bits))
3568 Result = DAG.getTargetConstant(CVal, Op.getValueType());
3572 // An absolute symbolic address or label reference.
3573 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
3574 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
3575 GA->getValueType(0));
3576 } else if (const BlockAddressSDNode *BA
3577 = dyn_cast<BlockAddressSDNode>(Op)) {
3578 Result = DAG.getTargetBlockAddress(BA->getBlockAddress(),
3579 BA->getValueType(0));
3580 } else if (const ExternalSymbolSDNode *ES
3581 = dyn_cast<ExternalSymbolSDNode>(Op)) {
3582 Result = DAG.getTargetExternalSymbol(ES->getSymbol(),
3583 ES->getValueType(0));
3589 if (const ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
3590 if (CFP->isExactlyValue(0.0)) {
3591 Result = DAG.getTargetConstantFP(0.0, CFP->getValueType(0));
3598 if (Result.getNode()) {
3599 Ops.push_back(Result);
3603 // It's an unknown constraint for us. Let generic code have a go.
3604 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3607 std::pair<unsigned, const TargetRegisterClass*>
3608 AArch64TargetLowering::getRegForInlineAsmConstraint(
3609 const std::string &Constraint,
3611 if (Constraint.size() == 1) {
3612 switch (Constraint[0]) {
3614 if (VT.getSizeInBits() <= 32)
3615 return std::make_pair(0U, &AArch64::GPR32RegClass);
3616 else if (VT == MVT::i64)
3617 return std::make_pair(0U, &AArch64::GPR64RegClass);
3621 return std::make_pair(0U, &AArch64::FPR16RegClass);
3622 else if (VT == MVT::f32)
3623 return std::make_pair(0U, &AArch64::FPR32RegClass);
3624 else if (VT.getSizeInBits() == 64)
3625 return std::make_pair(0U, &AArch64::FPR64RegClass);
3626 else if (VT.getSizeInBits() == 128)
3627 return std::make_pair(0U, &AArch64::FPR128RegClass);
3632 // Use the default implementation in TargetLowering to convert the register
3633 // constraint into a member of a register class.
3634 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);