Revert "Implement AArch64 vector load/store multiple N-element structure class SIMD...
[oota-llvm.git] / lib / Target / AArch64 / AArch64ISelLowering.cpp
1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that AArch64 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "aarch64-isel"
16 #include "AArch64.h"
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"
29
30 using namespace llvm;
31
32 static TargetLoweringObjectFile *createTLOF(AArch64TargetMachine &TM) {
33   const AArch64Subtarget *Subtarget = &TM.getSubtarget<AArch64Subtarget>();
34
35   if (Subtarget->isTargetLinux())
36     return new AArch64LinuxTargetObjectFile();
37   if (Subtarget->isTargetELF())
38     return new TargetLoweringObjectFileELF();
39   llvm_unreachable("unknown subtarget type");
40 }
41
42 AArch64TargetLowering::AArch64TargetLowering(AArch64TargetMachine &TM)
43   : TargetLowering(TM, createTLOF(TM)), Itins(TM.getInstrItineraryData()) {
44
45   const AArch64Subtarget *Subtarget = &TM.getSubtarget<AArch64Subtarget>();
46
47   // SIMD compares set the entire lane's bits to 1
48   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
49
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);
57
58   if (Subtarget->hasNEON()) {
59     // And the vectors
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);
77   }
78
79   computeRegisterProperties();
80
81   // We combine OR nodes for bitfield and NEON BSL operations.
82   setTargetDAGCombine(ISD::OR);
83
84   setTargetDAGCombine(ISD::AND);
85   setTargetDAGCombine(ISD::SRA);
86   setTargetDAGCombine(ISD::SRL);
87   setTargetDAGCombine(ISD::SHL);
88
89   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
90
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);
95
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);
100
101   // We'll lower globals to wrappers for selection.
102   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
103   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
104
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);
111
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);
116
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);
121
122   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
123
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);
128
129   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
130   setOperationAction(ISD::JumpTable, MVT::i32, Custom);
131   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
132
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);
137
138   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
139
140   setOperationAction(ISD::ROTL, MVT::i32, Expand);
141   setOperationAction(ISD::ROTL, MVT::i64, Expand);
142
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);
147
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);
152
153   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
154   setOperationAction(ISD::CTPOP, MVT::i64, Expand);
155
156   // Legal floating-point operations.
157   setOperationAction(ISD::FABS, MVT::f32, Legal);
158   setOperationAction(ISD::FABS, MVT::f64, Legal);
159
160   setOperationAction(ISD::FCEIL, MVT::f32, Legal);
161   setOperationAction(ISD::FCEIL, MVT::f64, Legal);
162
163   setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
164   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
165
166   setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
167   setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
168
169   setOperationAction(ISD::FNEG, MVT::f32, Legal);
170   setOperationAction(ISD::FNEG, MVT::f64, Legal);
171
172   setOperationAction(ISD::FRINT, MVT::f32, Legal);
173   setOperationAction(ISD::FRINT, MVT::f64, Legal);
174
175   setOperationAction(ISD::FSQRT, MVT::f32, Legal);
176   setOperationAction(ISD::FSQRT, MVT::f64, Legal);
177
178   setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
179   setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
180
181   setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
182   setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
183   setOperationAction(ISD::ConstantFP, MVT::f128, Legal);
184
185   // Illegal floating-point operations.
186   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
187   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
188
189   setOperationAction(ISD::FCOS, MVT::f32, Expand);
190   setOperationAction(ISD::FCOS, MVT::f64, Expand);
191
192   setOperationAction(ISD::FEXP, MVT::f32, Expand);
193   setOperationAction(ISD::FEXP, MVT::f64, Expand);
194
195   setOperationAction(ISD::FEXP2, MVT::f32, Expand);
196   setOperationAction(ISD::FEXP2, MVT::f64, Expand);
197
198   setOperationAction(ISD::FLOG, MVT::f32, Expand);
199   setOperationAction(ISD::FLOG, MVT::f64, Expand);
200
201   setOperationAction(ISD::FLOG2, MVT::f32, Expand);
202   setOperationAction(ISD::FLOG2, MVT::f64, Expand);
203
204   setOperationAction(ISD::FLOG10, MVT::f32, Expand);
205   setOperationAction(ISD::FLOG10, MVT::f64, Expand);
206
207   setOperationAction(ISD::FPOW, MVT::f32, Expand);
208   setOperationAction(ISD::FPOW, MVT::f64, Expand);
209
210   setOperationAction(ISD::FPOWI, MVT::f32, Expand);
211   setOperationAction(ISD::FPOWI, MVT::f64, Expand);
212
213   setOperationAction(ISD::FREM, MVT::f32, Expand);
214   setOperationAction(ISD::FREM, MVT::f64, Expand);
215
216   setOperationAction(ISD::FSIN, MVT::f32, Expand);
217   setOperationAction(ISD::FSIN, MVT::f64, Expand);
218
219   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
220   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
221
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);
247
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);
264
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);
271
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);
278
279   setExceptionPointerRegister(AArch64::X0);
280   setExceptionSelectorRegister(AArch64::X1);
281
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);
299
300     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
301     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i16, Custom);
302     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
303     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i32, Custom);
304     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f32, Custom);
305     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
306     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1f64, Custom);
307     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
308
309     setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Legal);
310     setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Legal);
311     setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Legal);
312     setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f32, Legal);
313     setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Legal);
314
315     setOperationAction(ISD::SETCC, MVT::v8i8, Custom);
316     setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
317     setOperationAction(ISD::SETCC, MVT::v4i16, Custom);
318     setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
319     setOperationAction(ISD::SETCC, MVT::v2i32, Custom);
320     setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
321     setOperationAction(ISD::SETCC, MVT::v1i64, Custom);
322     setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
323     setOperationAction(ISD::SETCC, MVT::v1f32, Custom);
324     setOperationAction(ISD::SETCC, MVT::v2f32, Custom);
325     setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
326     setOperationAction(ISD::SETCC, MVT::v1f64, Custom);
327     setOperationAction(ISD::SETCC, MVT::v2f64, Custom);
328   }
329 }
330
331 EVT AArch64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
332   // It's reasonably important that this value matches the "natural" legal
333   // promotion from i1 for scalar types. Otherwise LegalizeTypes can get itself
334   // in a twist (e.g. inserting an any_extend which then becomes i64 -> i64).
335   if (!VT.isVector()) return MVT::i32;
336   return VT.changeVectorElementTypeToInteger();
337 }
338
339 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
340                                   unsigned &LdrOpc,
341                                   unsigned &StrOpc) {
342   static const unsigned LoadBares[] = {AArch64::LDXR_byte, AArch64::LDXR_hword,
343                                        AArch64::LDXR_word, AArch64::LDXR_dword};
344   static const unsigned LoadAcqs[] = {AArch64::LDAXR_byte, AArch64::LDAXR_hword,
345                                      AArch64::LDAXR_word, AArch64::LDAXR_dword};
346   static const unsigned StoreBares[] = {AArch64::STXR_byte, AArch64::STXR_hword,
347                                        AArch64::STXR_word, AArch64::STXR_dword};
348   static const unsigned StoreRels[] = {AArch64::STLXR_byte,AArch64::STLXR_hword,
349                                      AArch64::STLXR_word, AArch64::STLXR_dword};
350
351   const unsigned *LoadOps, *StoreOps;
352   if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
353     LoadOps = LoadAcqs;
354   else
355     LoadOps = LoadBares;
356
357   if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
358     StoreOps = StoreRels;
359   else
360     StoreOps = StoreBares;
361
362   assert(isPowerOf2_32(Size) && Size <= 8 &&
363          "unsupported size for atomic binary op!");
364
365   LdrOpc = LoadOps[Log2_32(Size)];
366   StrOpc = StoreOps[Log2_32(Size)];
367 }
368
369 MachineBasicBlock *
370 AArch64TargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
371                                         unsigned Size,
372                                         unsigned BinOpcode) const {
373   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
374   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
375
376   const BasicBlock *LLVM_BB = BB->getBasicBlock();
377   MachineFunction *MF = BB->getParent();
378   MachineFunction::iterator It = BB;
379   ++It;
380
381   unsigned dest = MI->getOperand(0).getReg();
382   unsigned ptr = MI->getOperand(1).getReg();
383   unsigned incr = MI->getOperand(2).getReg();
384   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
385   DebugLoc dl = MI->getDebugLoc();
386
387   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
388
389   unsigned ldrOpc, strOpc;
390   getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
391
392   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
393   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
394   MF->insert(It, loopMBB);
395   MF->insert(It, exitMBB);
396
397   // Transfer the remainder of BB and its successor edges to exitMBB.
398   exitMBB->splice(exitMBB->begin(), BB,
399                   llvm::next(MachineBasicBlock::iterator(MI)),
400                   BB->end());
401   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
402
403   const TargetRegisterClass *TRC
404     = Size == 8 ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
405   unsigned scratch = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
406
407   //  thisMBB:
408   //   ...
409   //   fallthrough --> loopMBB
410   BB->addSuccessor(loopMBB);
411
412   //  loopMBB:
413   //   ldxr dest, ptr
414   //   <binop> scratch, dest, incr
415   //   stxr stxr_status, scratch, ptr
416   //   cbnz stxr_status, loopMBB
417   //   fallthrough --> exitMBB
418   BB = loopMBB;
419   BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
420   if (BinOpcode) {
421     // All arithmetic operations we'll be creating are designed to take an extra
422     // shift or extend operand, which we can conveniently set to zero.
423
424     // Operand order needs to go the other way for NAND.
425     if (BinOpcode == AArch64::BICwww_lsl || BinOpcode == AArch64::BICxxx_lsl)
426       BuildMI(BB, dl, TII->get(BinOpcode), scratch)
427         .addReg(incr).addReg(dest).addImm(0);
428     else
429       BuildMI(BB, dl, TII->get(BinOpcode), scratch)
430         .addReg(dest).addReg(incr).addImm(0);
431   }
432
433   // From the stxr, the register is GPR32; from the cmp it's GPR32wsp
434   unsigned stxr_status = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
435   MRI.constrainRegClass(stxr_status, &AArch64::GPR32wspRegClass);
436
437   BuildMI(BB, dl, TII->get(strOpc), stxr_status).addReg(scratch).addReg(ptr);
438   BuildMI(BB, dl, TII->get(AArch64::CBNZw))
439     .addReg(stxr_status).addMBB(loopMBB);
440
441   BB->addSuccessor(loopMBB);
442   BB->addSuccessor(exitMBB);
443
444   //  exitMBB:
445   //   ...
446   BB = exitMBB;
447
448   MI->eraseFromParent();   // The instruction is gone now.
449
450   return BB;
451 }
452
453 MachineBasicBlock *
454 AArch64TargetLowering::emitAtomicBinaryMinMax(MachineInstr *MI,
455                                               MachineBasicBlock *BB,
456                                               unsigned Size,
457                                               unsigned CmpOp,
458                                               A64CC::CondCodes Cond) const {
459   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
460
461   const BasicBlock *LLVM_BB = BB->getBasicBlock();
462   MachineFunction *MF = BB->getParent();
463   MachineFunction::iterator It = BB;
464   ++It;
465
466   unsigned dest = MI->getOperand(0).getReg();
467   unsigned ptr = MI->getOperand(1).getReg();
468   unsigned incr = MI->getOperand(2).getReg();
469   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
470
471   unsigned oldval = dest;
472   DebugLoc dl = MI->getDebugLoc();
473
474   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
475   const TargetRegisterClass *TRC, *TRCsp;
476   if (Size == 8) {
477     TRC = &AArch64::GPR64RegClass;
478     TRCsp = &AArch64::GPR64xspRegClass;
479   } else {
480     TRC = &AArch64::GPR32RegClass;
481     TRCsp = &AArch64::GPR32wspRegClass;
482   }
483
484   unsigned ldrOpc, strOpc;
485   getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
486
487   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
488   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
489   MF->insert(It, loopMBB);
490   MF->insert(It, exitMBB);
491
492   // Transfer the remainder of BB and its successor edges to exitMBB.
493   exitMBB->splice(exitMBB->begin(), BB,
494                   llvm::next(MachineBasicBlock::iterator(MI)),
495                   BB->end());
496   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
497
498   unsigned scratch = MRI.createVirtualRegister(TRC);
499   MRI.constrainRegClass(scratch, TRCsp);
500
501   //  thisMBB:
502   //   ...
503   //   fallthrough --> loopMBB
504   BB->addSuccessor(loopMBB);
505
506   //  loopMBB:
507   //   ldxr dest, ptr
508   //   cmp incr, dest (, sign extend if necessary)
509   //   csel scratch, dest, incr, cond
510   //   stxr stxr_status, scratch, ptr
511   //   cbnz stxr_status, loopMBB
512   //   fallthrough --> exitMBB
513   BB = loopMBB;
514   BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
515
516   // Build compare and cmov instructions.
517   MRI.constrainRegClass(incr, TRCsp);
518   BuildMI(BB, dl, TII->get(CmpOp))
519     .addReg(incr).addReg(oldval).addImm(0);
520
521   BuildMI(BB, dl, TII->get(Size == 8 ? AArch64::CSELxxxc : AArch64::CSELwwwc),
522           scratch)
523     .addReg(oldval).addReg(incr).addImm(Cond);
524
525   unsigned stxr_status = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
526   MRI.constrainRegClass(stxr_status, &AArch64::GPR32wspRegClass);
527
528   BuildMI(BB, dl, TII->get(strOpc), stxr_status)
529     .addReg(scratch).addReg(ptr);
530   BuildMI(BB, dl, TII->get(AArch64::CBNZw))
531     .addReg(stxr_status).addMBB(loopMBB);
532
533   BB->addSuccessor(loopMBB);
534   BB->addSuccessor(exitMBB);
535
536   //  exitMBB:
537   //   ...
538   BB = exitMBB;
539
540   MI->eraseFromParent();   // The instruction is gone now.
541
542   return BB;
543 }
544
545 MachineBasicBlock *
546 AArch64TargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
547                                          MachineBasicBlock *BB,
548                                          unsigned Size) const {
549   unsigned dest    = MI->getOperand(0).getReg();
550   unsigned ptr     = MI->getOperand(1).getReg();
551   unsigned oldval  = MI->getOperand(2).getReg();
552   unsigned newval  = MI->getOperand(3).getReg();
553   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
554   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
555   DebugLoc dl = MI->getDebugLoc();
556
557   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
558   const TargetRegisterClass *TRCsp;
559   TRCsp = Size == 8 ? &AArch64::GPR64xspRegClass : &AArch64::GPR32wspRegClass;
560
561   unsigned ldrOpc, strOpc;
562   getExclusiveOperation(Size, Ord, ldrOpc, strOpc);
563
564   MachineFunction *MF = BB->getParent();
565   const BasicBlock *LLVM_BB = BB->getBasicBlock();
566   MachineFunction::iterator It = BB;
567   ++It; // insert the new blocks after the current block
568
569   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
570   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
571   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
572   MF->insert(It, loop1MBB);
573   MF->insert(It, loop2MBB);
574   MF->insert(It, exitMBB);
575
576   // Transfer the remainder of BB and its successor edges to exitMBB.
577   exitMBB->splice(exitMBB->begin(), BB,
578                   llvm::next(MachineBasicBlock::iterator(MI)),
579                   BB->end());
580   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
581
582   //  thisMBB:
583   //   ...
584   //   fallthrough --> loop1MBB
585   BB->addSuccessor(loop1MBB);
586
587   // loop1MBB:
588   //   ldxr dest, [ptr]
589   //   cmp dest, oldval
590   //   b.ne exitMBB
591   BB = loop1MBB;
592   BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
593
594   unsigned CmpOp = Size == 8 ? AArch64::CMPxx_lsl : AArch64::CMPww_lsl;
595   MRI.constrainRegClass(dest, TRCsp);
596   BuildMI(BB, dl, TII->get(CmpOp))
597     .addReg(dest).addReg(oldval).addImm(0);
598   BuildMI(BB, dl, TII->get(AArch64::Bcc))
599     .addImm(A64CC::NE).addMBB(exitMBB);
600   BB->addSuccessor(loop2MBB);
601   BB->addSuccessor(exitMBB);
602
603   // loop2MBB:
604   //   strex stxr_status, newval, [ptr]
605   //   cbnz stxr_status, loop1MBB
606   BB = loop2MBB;
607   unsigned stxr_status = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
608   MRI.constrainRegClass(stxr_status, &AArch64::GPR32wspRegClass);
609
610   BuildMI(BB, dl, TII->get(strOpc), stxr_status).addReg(newval).addReg(ptr);
611   BuildMI(BB, dl, TII->get(AArch64::CBNZw))
612     .addReg(stxr_status).addMBB(loop1MBB);
613   BB->addSuccessor(loop1MBB);
614   BB->addSuccessor(exitMBB);
615
616   //  exitMBB:
617   //   ...
618   BB = exitMBB;
619
620   MI->eraseFromParent();   // The instruction is gone now.
621
622   return BB;
623 }
624
625 MachineBasicBlock *
626 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
627                                     MachineBasicBlock *MBB) const {
628   // We materialise the F128CSEL pseudo-instruction using conditional branches
629   // and loads, giving an instruciton sequence like:
630   //     str q0, [sp]
631   //     b.ne IfTrue
632   //     b Finish
633   // IfTrue:
634   //     str q1, [sp]
635   // Finish:
636   //     ldr q0, [sp]
637   //
638   // Using virtual registers would probably not be beneficial since COPY
639   // instructions are expensive for f128 (there's no actual instruction to
640   // implement them).
641   //
642   // An alternative would be to do an integer-CSEL on some address. E.g.:
643   //     mov x0, sp
644   //     add x1, sp, #16
645   //     str q0, [x0]
646   //     str q1, [x1]
647   //     csel x0, x0, x1, ne
648   //     ldr q0, [x0]
649   //
650   // It's unclear which approach is actually optimal.
651   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
652   MachineFunction *MF = MBB->getParent();
653   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
654   DebugLoc DL = MI->getDebugLoc();
655   MachineFunction::iterator It = MBB;
656   ++It;
657
658   unsigned DestReg = MI->getOperand(0).getReg();
659   unsigned IfTrueReg = MI->getOperand(1).getReg();
660   unsigned IfFalseReg = MI->getOperand(2).getReg();
661   unsigned CondCode = MI->getOperand(3).getImm();
662   bool NZCVKilled = MI->getOperand(4).isKill();
663
664   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
665   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
666   MF->insert(It, TrueBB);
667   MF->insert(It, EndBB);
668
669   // Transfer rest of current basic-block to EndBB
670   EndBB->splice(EndBB->begin(), MBB,
671                 llvm::next(MachineBasicBlock::iterator(MI)),
672                 MBB->end());
673   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
674
675   // We need somewhere to store the f128 value needed.
676   int ScratchFI = MF->getFrameInfo()->CreateSpillStackObject(16, 16);
677
678   //     [... start of incoming MBB ...]
679   //     str qIFFALSE, [sp]
680   //     b.cc IfTrue
681   //     b Done
682   BuildMI(MBB, DL, TII->get(AArch64::LSFP128_STR))
683     .addReg(IfFalseReg)
684     .addFrameIndex(ScratchFI)
685     .addImm(0);
686   BuildMI(MBB, DL, TII->get(AArch64::Bcc))
687     .addImm(CondCode)
688     .addMBB(TrueBB);
689   BuildMI(MBB, DL, TII->get(AArch64::Bimm))
690     .addMBB(EndBB);
691   MBB->addSuccessor(TrueBB);
692   MBB->addSuccessor(EndBB);
693
694   // IfTrue:
695   //     str qIFTRUE, [sp]
696   BuildMI(TrueBB, DL, TII->get(AArch64::LSFP128_STR))
697     .addReg(IfTrueReg)
698     .addFrameIndex(ScratchFI)
699     .addImm(0);
700
701   // Note: fallthrough. We can rely on LLVM adding a branch if it reorders the
702   // blocks.
703   TrueBB->addSuccessor(EndBB);
704
705   // Done:
706   //     ldr qDEST, [sp]
707   //     [... rest of incoming MBB ...]
708   if (!NZCVKilled)
709     EndBB->addLiveIn(AArch64::NZCV);
710   MachineInstr *StartOfEnd = EndBB->begin();
711   BuildMI(*EndBB, StartOfEnd, DL, TII->get(AArch64::LSFP128_LDR), DestReg)
712     .addFrameIndex(ScratchFI)
713     .addImm(0);
714
715   MI->eraseFromParent();
716   return EndBB;
717 }
718
719 MachineBasicBlock *
720 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
721                                                  MachineBasicBlock *MBB) const {
722   switch (MI->getOpcode()) {
723   default: llvm_unreachable("Unhandled instruction with custom inserter");
724   case AArch64::F128CSEL:
725     return EmitF128CSEL(MI, MBB);
726   case AArch64::ATOMIC_LOAD_ADD_I8:
727     return emitAtomicBinary(MI, MBB, 1, AArch64::ADDwww_lsl);
728   case AArch64::ATOMIC_LOAD_ADD_I16:
729     return emitAtomicBinary(MI, MBB, 2, AArch64::ADDwww_lsl);
730   case AArch64::ATOMIC_LOAD_ADD_I32:
731     return emitAtomicBinary(MI, MBB, 4, AArch64::ADDwww_lsl);
732   case AArch64::ATOMIC_LOAD_ADD_I64:
733     return emitAtomicBinary(MI, MBB, 8, AArch64::ADDxxx_lsl);
734
735   case AArch64::ATOMIC_LOAD_SUB_I8:
736     return emitAtomicBinary(MI, MBB, 1, AArch64::SUBwww_lsl);
737   case AArch64::ATOMIC_LOAD_SUB_I16:
738     return emitAtomicBinary(MI, MBB, 2, AArch64::SUBwww_lsl);
739   case AArch64::ATOMIC_LOAD_SUB_I32:
740     return emitAtomicBinary(MI, MBB, 4, AArch64::SUBwww_lsl);
741   case AArch64::ATOMIC_LOAD_SUB_I64:
742     return emitAtomicBinary(MI, MBB, 8, AArch64::SUBxxx_lsl);
743
744   case AArch64::ATOMIC_LOAD_AND_I8:
745     return emitAtomicBinary(MI, MBB, 1, AArch64::ANDwww_lsl);
746   case AArch64::ATOMIC_LOAD_AND_I16:
747     return emitAtomicBinary(MI, MBB, 2, AArch64::ANDwww_lsl);
748   case AArch64::ATOMIC_LOAD_AND_I32:
749     return emitAtomicBinary(MI, MBB, 4, AArch64::ANDwww_lsl);
750   case AArch64::ATOMIC_LOAD_AND_I64:
751     return emitAtomicBinary(MI, MBB, 8, AArch64::ANDxxx_lsl);
752
753   case AArch64::ATOMIC_LOAD_OR_I8:
754     return emitAtomicBinary(MI, MBB, 1, AArch64::ORRwww_lsl);
755   case AArch64::ATOMIC_LOAD_OR_I16:
756     return emitAtomicBinary(MI, MBB, 2, AArch64::ORRwww_lsl);
757   case AArch64::ATOMIC_LOAD_OR_I32:
758     return emitAtomicBinary(MI, MBB, 4, AArch64::ORRwww_lsl);
759   case AArch64::ATOMIC_LOAD_OR_I64:
760     return emitAtomicBinary(MI, MBB, 8, AArch64::ORRxxx_lsl);
761
762   case AArch64::ATOMIC_LOAD_XOR_I8:
763     return emitAtomicBinary(MI, MBB, 1, AArch64::EORwww_lsl);
764   case AArch64::ATOMIC_LOAD_XOR_I16:
765     return emitAtomicBinary(MI, MBB, 2, AArch64::EORwww_lsl);
766   case AArch64::ATOMIC_LOAD_XOR_I32:
767     return emitAtomicBinary(MI, MBB, 4, AArch64::EORwww_lsl);
768   case AArch64::ATOMIC_LOAD_XOR_I64:
769     return emitAtomicBinary(MI, MBB, 8, AArch64::EORxxx_lsl);
770
771   case AArch64::ATOMIC_LOAD_NAND_I8:
772     return emitAtomicBinary(MI, MBB, 1, AArch64::BICwww_lsl);
773   case AArch64::ATOMIC_LOAD_NAND_I16:
774     return emitAtomicBinary(MI, MBB, 2, AArch64::BICwww_lsl);
775   case AArch64::ATOMIC_LOAD_NAND_I32:
776     return emitAtomicBinary(MI, MBB, 4, AArch64::BICwww_lsl);
777   case AArch64::ATOMIC_LOAD_NAND_I64:
778     return emitAtomicBinary(MI, MBB, 8, AArch64::BICxxx_lsl);
779
780   case AArch64::ATOMIC_LOAD_MIN_I8:
781     return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_sxtb, A64CC::GT);
782   case AArch64::ATOMIC_LOAD_MIN_I16:
783     return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_sxth, A64CC::GT);
784   case AArch64::ATOMIC_LOAD_MIN_I32:
785     return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::GT);
786   case AArch64::ATOMIC_LOAD_MIN_I64:
787     return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::GT);
788
789   case AArch64::ATOMIC_LOAD_MAX_I8:
790     return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_sxtb, A64CC::LT);
791   case AArch64::ATOMIC_LOAD_MAX_I16:
792     return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_sxth, A64CC::LT);
793   case AArch64::ATOMIC_LOAD_MAX_I32:
794     return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::LT);
795   case AArch64::ATOMIC_LOAD_MAX_I64:
796     return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::LT);
797
798   case AArch64::ATOMIC_LOAD_UMIN_I8:
799     return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_uxtb, A64CC::HI);
800   case AArch64::ATOMIC_LOAD_UMIN_I16:
801     return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_uxth, A64CC::HI);
802   case AArch64::ATOMIC_LOAD_UMIN_I32:
803     return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::HI);
804   case AArch64::ATOMIC_LOAD_UMIN_I64:
805     return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::HI);
806
807   case AArch64::ATOMIC_LOAD_UMAX_I8:
808     return emitAtomicBinaryMinMax(MI, MBB, 1, AArch64::CMPww_uxtb, A64CC::LO);
809   case AArch64::ATOMIC_LOAD_UMAX_I16:
810     return emitAtomicBinaryMinMax(MI, MBB, 2, AArch64::CMPww_uxth, A64CC::LO);
811   case AArch64::ATOMIC_LOAD_UMAX_I32:
812     return emitAtomicBinaryMinMax(MI, MBB, 4, AArch64::CMPww_lsl, A64CC::LO);
813   case AArch64::ATOMIC_LOAD_UMAX_I64:
814     return emitAtomicBinaryMinMax(MI, MBB, 8, AArch64::CMPxx_lsl, A64CC::LO);
815
816   case AArch64::ATOMIC_SWAP_I8:
817     return emitAtomicBinary(MI, MBB, 1, 0);
818   case AArch64::ATOMIC_SWAP_I16:
819     return emitAtomicBinary(MI, MBB, 2, 0);
820   case AArch64::ATOMIC_SWAP_I32:
821     return emitAtomicBinary(MI, MBB, 4, 0);
822   case AArch64::ATOMIC_SWAP_I64:
823     return emitAtomicBinary(MI, MBB, 8, 0);
824
825   case AArch64::ATOMIC_CMP_SWAP_I8:
826     return emitAtomicCmpSwap(MI, MBB, 1);
827   case AArch64::ATOMIC_CMP_SWAP_I16:
828     return emitAtomicCmpSwap(MI, MBB, 2);
829   case AArch64::ATOMIC_CMP_SWAP_I32:
830     return emitAtomicCmpSwap(MI, MBB, 4);
831   case AArch64::ATOMIC_CMP_SWAP_I64:
832     return emitAtomicCmpSwap(MI, MBB, 8);
833   }
834 }
835
836
837 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
838   switch (Opcode) {
839   case AArch64ISD::BR_CC:          return "AArch64ISD::BR_CC";
840   case AArch64ISD::Call:           return "AArch64ISD::Call";
841   case AArch64ISD::FPMOV:          return "AArch64ISD::FPMOV";
842   case AArch64ISD::GOTLoad:        return "AArch64ISD::GOTLoad";
843   case AArch64ISD::BFI:            return "AArch64ISD::BFI";
844   case AArch64ISD::EXTR:           return "AArch64ISD::EXTR";
845   case AArch64ISD::Ret:            return "AArch64ISD::Ret";
846   case AArch64ISD::SBFX:           return "AArch64ISD::SBFX";
847   case AArch64ISD::SELECT_CC:      return "AArch64ISD::SELECT_CC";
848   case AArch64ISD::SETCC:          return "AArch64ISD::SETCC";
849   case AArch64ISD::TC_RETURN:      return "AArch64ISD::TC_RETURN";
850   case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
851   case AArch64ISD::TLSDESCCALL:    return "AArch64ISD::TLSDESCCALL";
852   case AArch64ISD::WrapperLarge:   return "AArch64ISD::WrapperLarge";
853   case AArch64ISD::WrapperSmall:   return "AArch64ISD::WrapperSmall";
854
855   case AArch64ISD::NEON_BSL:
856     return "AArch64ISD::NEON_BSL";
857   case AArch64ISD::NEON_MOVIMM:
858     return "AArch64ISD::NEON_MOVIMM";
859   case AArch64ISD::NEON_MVNIMM:
860     return "AArch64ISD::NEON_MVNIMM";
861   case AArch64ISD::NEON_FMOVIMM:
862     return "AArch64ISD::NEON_FMOVIMM";
863   case AArch64ISD::NEON_CMP:
864     return "AArch64ISD::NEON_CMP";
865   case AArch64ISD::NEON_CMPZ:
866     return "AArch64ISD::NEON_CMPZ";
867   case AArch64ISD::NEON_TST:
868     return "AArch64ISD::NEON_TST";
869   case AArch64ISD::NEON_DUPIMM:
870     return "AArch64ISD::NEON_DUPIMM";
871   case AArch64ISD::NEON_QSHLs:
872     return "AArch64ISD::NEON_QSHLs";
873   case AArch64ISD::NEON_QSHLu:
874     return "AArch64ISD::NEON_QSHLu";
875   case AArch64ISD::NEON_VDUPLANE:
876     return "AArch64ISD::NEON_VDUPLANE";
877   default:
878     return NULL;
879   }
880 }
881
882 static const uint16_t AArch64FPRArgRegs[] = {
883   AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
884   AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7
885 };
886 static const unsigned NumFPRArgRegs = llvm::array_lengthof(AArch64FPRArgRegs);
887
888 static const uint16_t AArch64ArgRegs[] = {
889   AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3,
890   AArch64::X4, AArch64::X5, AArch64::X6, AArch64::X7
891 };
892 static const unsigned NumArgRegs = llvm::array_lengthof(AArch64ArgRegs);
893
894 static bool CC_AArch64NoMoreRegs(unsigned ValNo, MVT ValVT, MVT LocVT,
895                                  CCValAssign::LocInfo LocInfo,
896                                  ISD::ArgFlagsTy ArgFlags, CCState &State) {
897   // Mark all remaining general purpose registers as allocated. We don't
898   // backtrack: if (for example) an i128 gets put on the stack, no subsequent
899   // i64 will go in registers (C.11).
900   for (unsigned i = 0; i < NumArgRegs; ++i)
901     State.AllocateReg(AArch64ArgRegs[i]);
902
903   return false;
904 }
905
906 #include "AArch64GenCallingConv.inc"
907
908 CCAssignFn *AArch64TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
909
910   switch(CC) {
911   default: llvm_unreachable("Unsupported calling convention");
912   case CallingConv::Fast:
913   case CallingConv::C:
914     return CC_A64_APCS;
915   }
916 }
917
918 void
919 AArch64TargetLowering::SaveVarArgRegisters(CCState &CCInfo, SelectionDAG &DAG,
920                                            SDLoc DL, SDValue &Chain) const {
921   MachineFunction &MF = DAG.getMachineFunction();
922   MachineFrameInfo *MFI = MF.getFrameInfo();
923   AArch64MachineFunctionInfo *FuncInfo
924     = MF.getInfo<AArch64MachineFunctionInfo>();
925
926   SmallVector<SDValue, 8> MemOps;
927
928   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(AArch64ArgRegs,
929                                                          NumArgRegs);
930   unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(AArch64FPRArgRegs,
931                                                          NumFPRArgRegs);
932
933   unsigned GPRSaveSize = 8 * (NumArgRegs - FirstVariadicGPR);
934   int GPRIdx = 0;
935   if (GPRSaveSize != 0) {
936     GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
937
938     SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
939
940     for (unsigned i = FirstVariadicGPR; i < NumArgRegs; ++i) {
941       unsigned VReg = MF.addLiveIn(AArch64ArgRegs[i], &AArch64::GPR64RegClass);
942       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
943       SDValue Store = DAG.getStore(Val.getValue(1), DL, Val, FIN,
944                                    MachinePointerInfo::getStack(i * 8),
945                                    false, false, 0);
946       MemOps.push_back(Store);
947       FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
948                         DAG.getConstant(8, getPointerTy()));
949     }
950   }
951
952   unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
953   int FPRIdx = 0;
954   if (FPRSaveSize != 0) {
955     FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
956
957     SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
958
959     for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
960       unsigned VReg = MF.addLiveIn(AArch64FPRArgRegs[i],
961                                    &AArch64::FPR128RegClass);
962       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
963       SDValue Store = DAG.getStore(Val.getValue(1), DL, Val, FIN,
964                                    MachinePointerInfo::getStack(i * 16),
965                                    false, false, 0);
966       MemOps.push_back(Store);
967       FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
968                         DAG.getConstant(16, getPointerTy()));
969     }
970   }
971
972   int StackIdx = MFI->CreateFixedObject(8, CCInfo.getNextStackOffset(), true);
973
974   FuncInfo->setVariadicStackIdx(StackIdx);
975   FuncInfo->setVariadicGPRIdx(GPRIdx);
976   FuncInfo->setVariadicGPRSize(GPRSaveSize);
977   FuncInfo->setVariadicFPRIdx(FPRIdx);
978   FuncInfo->setVariadicFPRSize(FPRSaveSize);
979
980   if (!MemOps.empty()) {
981     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
982                         MemOps.size());
983   }
984 }
985
986
987 SDValue
988 AArch64TargetLowering::LowerFormalArguments(SDValue Chain,
989                                       CallingConv::ID CallConv, bool isVarArg,
990                                       const SmallVectorImpl<ISD::InputArg> &Ins,
991                                       SDLoc dl, SelectionDAG &DAG,
992                                       SmallVectorImpl<SDValue> &InVals) const {
993   MachineFunction &MF = DAG.getMachineFunction();
994   AArch64MachineFunctionInfo *FuncInfo
995     = MF.getInfo<AArch64MachineFunctionInfo>();
996   MachineFrameInfo *MFI = MF.getFrameInfo();
997   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
998
999   SmallVector<CCValAssign, 16> ArgLocs;
1000   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1001                  getTargetMachine(), ArgLocs, *DAG.getContext());
1002   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1003
1004   SmallVector<SDValue, 16> ArgValues;
1005
1006   SDValue ArgValue;
1007   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1008     CCValAssign &VA = ArgLocs[i];
1009     ISD::ArgFlagsTy Flags = Ins[i].Flags;
1010
1011     if (Flags.isByVal()) {
1012       // Byval is used for small structs and HFAs in the PCS, but the system
1013       // should work in a non-compliant manner for larger structs.
1014       EVT PtrTy = getPointerTy();
1015       int Size = Flags.getByValSize();
1016       unsigned NumRegs = (Size + 7) / 8;
1017
1018       unsigned FrameIdx = MFI->CreateFixedObject(8 * NumRegs,
1019                                                  VA.getLocMemOffset(),
1020                                                  false);
1021       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrTy);
1022       InVals.push_back(FrameIdxN);
1023
1024       continue;
1025     } else if (VA.isRegLoc()) {
1026       MVT RegVT = VA.getLocVT();
1027       const TargetRegisterClass *RC = getRegClassFor(RegVT);
1028       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1029
1030       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1031     } else { // VA.isRegLoc()
1032       assert(VA.isMemLoc());
1033
1034       int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
1035                                       VA.getLocMemOffset(), true);
1036
1037       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1038       ArgValue = DAG.getLoad(VA.getLocVT(), dl, Chain, FIN,
1039                              MachinePointerInfo::getFixedStack(FI),
1040                              false, false, false, 0);
1041
1042
1043     }
1044
1045     switch (VA.getLocInfo()) {
1046     default: llvm_unreachable("Unknown loc info!");
1047     case CCValAssign::Full: break;
1048     case CCValAssign::BCvt:
1049       ArgValue = DAG.getNode(ISD::BITCAST,dl, VA.getValVT(), ArgValue);
1050       break;
1051     case CCValAssign::SExt:
1052     case CCValAssign::ZExt:
1053     case CCValAssign::AExt: {
1054       unsigned DestSize = VA.getValVT().getSizeInBits();
1055       unsigned DestSubReg;
1056
1057       switch (DestSize) {
1058       case 8: DestSubReg = AArch64::sub_8; break;
1059       case 16: DestSubReg = AArch64::sub_16; break;
1060       case 32: DestSubReg = AArch64::sub_32; break;
1061       case 64: DestSubReg = AArch64::sub_64; break;
1062       default: llvm_unreachable("Unexpected argument promotion");
1063       }
1064
1065       ArgValue = SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl,
1066                                    VA.getValVT(), ArgValue,
1067                                    DAG.getTargetConstant(DestSubReg, MVT::i32)),
1068                          0);
1069       break;
1070     }
1071     }
1072
1073     InVals.push_back(ArgValue);
1074   }
1075
1076   if (isVarArg)
1077     SaveVarArgRegisters(CCInfo, DAG, dl, Chain);
1078
1079   unsigned StackArgSize = CCInfo.getNextStackOffset();
1080   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
1081     // This is a non-standard ABI so by fiat I say we're allowed to make full
1082     // use of the stack area to be popped, which must be aligned to 16 bytes in
1083     // any case:
1084     StackArgSize = RoundUpToAlignment(StackArgSize, 16);
1085
1086     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
1087     // a multiple of 16.
1088     FuncInfo->setArgumentStackToRestore(StackArgSize);
1089
1090     // This realignment carries over to the available bytes below. Our own
1091     // callers will guarantee the space is free by giving an aligned value to
1092     // CALLSEQ_START.
1093   }
1094   // Even if we're not expected to free up the space, it's useful to know how
1095   // much is there while considering tail calls (because we can reuse it).
1096   FuncInfo->setBytesInStackArgArea(StackArgSize);
1097
1098   return Chain;
1099 }
1100
1101 SDValue
1102 AArch64TargetLowering::LowerReturn(SDValue Chain,
1103                                    CallingConv::ID CallConv, bool isVarArg,
1104                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
1105                                    const SmallVectorImpl<SDValue> &OutVals,
1106                                    SDLoc dl, SelectionDAG &DAG) const {
1107   // CCValAssign - represent the assignment of the return value to a location.
1108   SmallVector<CCValAssign, 16> RVLocs;
1109
1110   // CCState - Info about the registers and stack slots.
1111   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1112                  getTargetMachine(), RVLocs, *DAG.getContext());
1113
1114   // Analyze outgoing return values.
1115   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv));
1116
1117   SDValue Flag;
1118   SmallVector<SDValue, 4> RetOps(1, Chain);
1119
1120   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1121     // PCS: "If the type, T, of the result of a function is such that
1122     // void func(T arg) would require that arg be passed as a value in a
1123     // register (or set of registers) according to the rules in 5.4, then the
1124     // result is returned in the same registers as would be used for such an
1125     // argument.
1126     //
1127     // Otherwise, the caller shall reserve a block of memory of sufficient
1128     // size and alignment to hold the result. The address of the memory block
1129     // shall be passed as an additional argument to the function in x8."
1130     //
1131     // This is implemented in two places. The register-return values are dealt
1132     // with here, more complex returns are passed as an sret parameter, which
1133     // means we don't have to worry about it during actual return.
1134     CCValAssign &VA = RVLocs[i];
1135     assert(VA.isRegLoc() && "Only register-returns should be created by PCS");
1136
1137
1138     SDValue Arg = OutVals[i];
1139
1140     // There's no convenient note in the ABI about this as there is for normal
1141     // arguments, but it says return values are passed in the same registers as
1142     // an argument would be. I believe that includes the comments about
1143     // unspecified higher bits, putting the burden of widening on the *caller*
1144     // for return values.
1145     switch (VA.getLocInfo()) {
1146     default: llvm_unreachable("Unknown loc info");
1147     case CCValAssign::Full: break;
1148     case CCValAssign::SExt:
1149     case CCValAssign::ZExt:
1150     case CCValAssign::AExt:
1151       // Floating-point values should only be extended when they're going into
1152       // memory, which can't happen here so an integer extend is acceptable.
1153       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1154       break;
1155     case CCValAssign::BCvt:
1156       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1157       break;
1158     }
1159
1160     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1161     Flag = Chain.getValue(1);
1162     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1163   }
1164
1165   RetOps[0] = Chain;  // Update chain.
1166
1167   // Add the flag if we have it.
1168   if (Flag.getNode())
1169     RetOps.push_back(Flag);
1170
1171   return DAG.getNode(AArch64ISD::Ret, dl, MVT::Other,
1172                      &RetOps[0], RetOps.size());
1173 }
1174
1175 SDValue
1176 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
1177                                  SmallVectorImpl<SDValue> &InVals) const {
1178   SelectionDAG &DAG                     = CLI.DAG;
1179   SDLoc &dl                             = CLI.DL;
1180   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1181   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1182   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1183   SDValue Chain                         = CLI.Chain;
1184   SDValue Callee                        = CLI.Callee;
1185   bool &IsTailCall                      = CLI.IsTailCall;
1186   CallingConv::ID CallConv              = CLI.CallConv;
1187   bool IsVarArg                         = CLI.IsVarArg;
1188
1189   MachineFunction &MF = DAG.getMachineFunction();
1190   AArch64MachineFunctionInfo *FuncInfo
1191     = MF.getInfo<AArch64MachineFunctionInfo>();
1192   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
1193   bool IsStructRet = !Outs.empty() && Outs[0].Flags.isSRet();
1194   bool IsSibCall = false;
1195
1196   if (IsTailCall) {
1197     IsTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1198                     IsVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1199                                                    Outs, OutVals, Ins, DAG);
1200
1201     // A sibling call is one where we're under the usual C ABI and not planning
1202     // to change that but can still do a tail call:
1203     if (!TailCallOpt && IsTailCall)
1204       IsSibCall = true;
1205   }
1206
1207   SmallVector<CCValAssign, 16> ArgLocs;
1208   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
1209                  getTargetMachine(), ArgLocs, *DAG.getContext());
1210   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1211
1212   // On AArch64 (and all other architectures I'm aware of) the most this has to
1213   // do is adjust the stack pointer.
1214   unsigned NumBytes = RoundUpToAlignment(CCInfo.getNextStackOffset(), 16);
1215   if (IsSibCall) {
1216     // Since we're not changing the ABI to make this a tail call, the memory
1217     // operands are already available in the caller's incoming argument space.
1218     NumBytes = 0;
1219   }
1220
1221   // FPDiff is the byte offset of the call's argument area from the callee's.
1222   // Stores to callee stack arguments will be placed in FixedStackSlots offset
1223   // by this amount for a tail call. In a sibling call it must be 0 because the
1224   // caller will deallocate the entire stack and the callee still expects its
1225   // arguments to begin at SP+0. Completely unused for non-tail calls.
1226   int FPDiff = 0;
1227
1228   if (IsTailCall && !IsSibCall) {
1229     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
1230
1231     // FPDiff will be negative if this tail call requires more space than we
1232     // would automatically have in our incoming argument space. Positive if we
1233     // can actually shrink the stack.
1234     FPDiff = NumReusableBytes - NumBytes;
1235
1236     // The stack pointer must be 16-byte aligned at all times it's used for a
1237     // memory operation, which in practice means at *all* times and in
1238     // particular across call boundaries. Therefore our own arguments started at
1239     // a 16-byte aligned SP and the delta applied for the tail call should
1240     // satisfy the same constraint.
1241     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
1242   }
1243
1244   if (!IsSibCall)
1245     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1246                                  dl);
1247
1248   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, AArch64::XSP,
1249                                         getPointerTy());
1250
1251   SmallVector<SDValue, 8> MemOpChains;
1252   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1253
1254   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1255     CCValAssign &VA = ArgLocs[i];
1256     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1257     SDValue Arg = OutVals[i];
1258
1259     // Callee does the actual widening, so all extensions just use an implicit
1260     // definition of the rest of the Loc. Aesthetically, this would be nicer as
1261     // an ANY_EXTEND, but that isn't valid for floating-point types and this
1262     // alternative works on integer types too.
1263     switch (VA.getLocInfo()) {
1264     default: llvm_unreachable("Unknown loc info!");
1265     case CCValAssign::Full: break;
1266     case CCValAssign::SExt:
1267     case CCValAssign::ZExt:
1268     case CCValAssign::AExt: {
1269       unsigned SrcSize = VA.getValVT().getSizeInBits();
1270       unsigned SrcSubReg;
1271
1272       switch (SrcSize) {
1273       case 8: SrcSubReg = AArch64::sub_8; break;
1274       case 16: SrcSubReg = AArch64::sub_16; break;
1275       case 32: SrcSubReg = AArch64::sub_32; break;
1276       case 64: SrcSubReg = AArch64::sub_64; break;
1277       default: llvm_unreachable("Unexpected argument promotion");
1278       }
1279
1280       Arg = SDValue(DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl,
1281                                     VA.getLocVT(),
1282                                     DAG.getUNDEF(VA.getLocVT()),
1283                                     Arg,
1284                                     DAG.getTargetConstant(SrcSubReg, MVT::i32)),
1285                     0);
1286
1287       break;
1288     }
1289     case CCValAssign::BCvt:
1290       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1291       break;
1292     }
1293
1294     if (VA.isRegLoc()) {
1295       // A normal register (sub-) argument. For now we just note it down because
1296       // we want to copy things into registers as late as possible to avoid
1297       // register-pressure (and possibly worse).
1298       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1299       continue;
1300     }
1301
1302     assert(VA.isMemLoc() && "unexpected argument location");
1303
1304     SDValue DstAddr;
1305     MachinePointerInfo DstInfo;
1306     if (IsTailCall) {
1307       uint32_t OpSize = Flags.isByVal() ? Flags.getByValSize() :
1308                                           VA.getLocVT().getSizeInBits();
1309       OpSize = (OpSize + 7) / 8;
1310       int32_t Offset = VA.getLocMemOffset() + FPDiff;
1311       int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
1312
1313       DstAddr = DAG.getFrameIndex(FI, getPointerTy());
1314       DstInfo = MachinePointerInfo::getFixedStack(FI);
1315
1316       // Make sure any stack arguments overlapping with where we're storing are
1317       // loaded before this eventual operation. Otherwise they'll be clobbered.
1318       Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
1319     } else {
1320       SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset());
1321
1322       DstAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1323       DstInfo = MachinePointerInfo::getStack(VA.getLocMemOffset());
1324     }
1325
1326     if (Flags.isByVal()) {
1327       SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i64);
1328       SDValue Cpy = DAG.getMemcpy(Chain, dl, DstAddr, Arg, SizeNode,
1329                                   Flags.getByValAlign(),
1330                                   /*isVolatile = */ false,
1331                                   /*alwaysInline = */ false,
1332                                   DstInfo, MachinePointerInfo(0));
1333       MemOpChains.push_back(Cpy);
1334     } else {
1335       // Normal stack argument, put it where it's needed.
1336       SDValue Store = DAG.getStore(Chain, dl, Arg, DstAddr, DstInfo,
1337                                    false, false, 0);
1338       MemOpChains.push_back(Store);
1339     }
1340   }
1341
1342   // The loads and stores generated above shouldn't clash with each
1343   // other. Combining them with this TokenFactor notes that fact for the rest of
1344   // the backend.
1345   if (!MemOpChains.empty())
1346     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1347                         &MemOpChains[0], MemOpChains.size());
1348
1349   // Most of the rest of the instructions need to be glued together; we don't
1350   // want assignments to actual registers used by a call to be rearranged by a
1351   // well-meaning scheduler.
1352   SDValue InFlag;
1353
1354   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1355     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1356                              RegsToPass[i].second, InFlag);
1357     InFlag = Chain.getValue(1);
1358   }
1359
1360   // The linker is responsible for inserting veneers when necessary to put a
1361   // function call destination in range, so we don't need to bother with a
1362   // wrapper here.
1363   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1364     const GlobalValue *GV = G->getGlobal();
1365     Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy());
1366   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1367     const char *Sym = S->getSymbol();
1368     Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy());
1369   }
1370
1371   // We don't usually want to end the call-sequence here because we would tidy
1372   // the frame up *after* the call, however in the ABI-changing tail-call case
1373   // we've carefully laid out the parameters so that when sp is reset they'll be
1374   // in the correct location.
1375   if (IsTailCall && !IsSibCall) {
1376     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1377                                DAG.getIntPtrConstant(0, true), InFlag, dl);
1378     InFlag = Chain.getValue(1);
1379   }
1380
1381   // We produce the following DAG scheme for the actual call instruction:
1382   //     (AArch64Call Chain, Callee, reg1, ..., regn, preserveMask, inflag?
1383   //
1384   // Most arguments aren't going to be used and just keep the values live as
1385   // far as LLVM is concerned. It's expected to be selected as simply "bl
1386   // callee" (for a direct, non-tail call).
1387   std::vector<SDValue> Ops;
1388   Ops.push_back(Chain);
1389   Ops.push_back(Callee);
1390
1391   if (IsTailCall) {
1392     // Each tail call may have to adjust the stack by a different amount, so
1393     // this information must travel along with the operation for eventual
1394     // consumption by emitEpilogue.
1395     Ops.push_back(DAG.getTargetConstant(FPDiff, MVT::i32));
1396   }
1397
1398   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1399     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1400                                   RegsToPass[i].second.getValueType()));
1401
1402
1403   // Add a register mask operand representing the call-preserved registers. This
1404   // is used later in codegen to constrain register-allocation.
1405   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1406   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1407   assert(Mask && "Missing call preserved mask for calling convention");
1408   Ops.push_back(DAG.getRegisterMask(Mask));
1409
1410   // If we needed glue, put it in as the last argument.
1411   if (InFlag.getNode())
1412     Ops.push_back(InFlag);
1413
1414   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1415
1416   if (IsTailCall) {
1417     return DAG.getNode(AArch64ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1418   }
1419
1420   Chain = DAG.getNode(AArch64ISD::Call, dl, NodeTys, &Ops[0], Ops.size());
1421   InFlag = Chain.getValue(1);
1422
1423   // Now we can reclaim the stack, just as well do it before working out where
1424   // our return value is.
1425   if (!IsSibCall) {
1426     uint64_t CalleePopBytes
1427       = DoesCalleeRestoreStack(CallConv, TailCallOpt) ? NumBytes : 0;
1428
1429     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1430                                DAG.getIntPtrConstant(CalleePopBytes, true),
1431                                InFlag, dl);
1432     InFlag = Chain.getValue(1);
1433   }
1434
1435   return LowerCallResult(Chain, InFlag, CallConv,
1436                          IsVarArg, Ins, dl, DAG, InVals);
1437 }
1438
1439 SDValue
1440 AArch64TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1441                                       CallingConv::ID CallConv, bool IsVarArg,
1442                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1443                                       SDLoc dl, SelectionDAG &DAG,
1444                                       SmallVectorImpl<SDValue> &InVals) const {
1445   // Assign locations to each value returned by this call.
1446   SmallVector<CCValAssign, 16> RVLocs;
1447   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
1448                  getTargetMachine(), RVLocs, *DAG.getContext());
1449   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForNode(CallConv));
1450
1451   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1452     CCValAssign VA = RVLocs[i];
1453
1454     // Return values that are too big to fit into registers should use an sret
1455     // pointer, so this can be a lot simpler than the main argument code.
1456     assert(VA.isRegLoc() && "Memory locations not expected for call return");
1457
1458     SDValue Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1459                                      InFlag);
1460     Chain = Val.getValue(1);
1461     InFlag = Val.getValue(2);
1462
1463     switch (VA.getLocInfo()) {
1464     default: llvm_unreachable("Unknown loc info!");
1465     case CCValAssign::Full: break;
1466     case CCValAssign::BCvt:
1467       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1468       break;
1469     case CCValAssign::ZExt:
1470     case CCValAssign::SExt:
1471     case CCValAssign::AExt:
1472       // Floating-point arguments only get extended/truncated if they're going
1473       // in memory, so using the integer operation is acceptable here.
1474       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
1475       break;
1476     }
1477
1478     InVals.push_back(Val);
1479   }
1480
1481   return Chain;
1482 }
1483
1484 bool
1485 AArch64TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1486                                     CallingConv::ID CalleeCC,
1487                                     bool IsVarArg,
1488                                     bool IsCalleeStructRet,
1489                                     bool IsCallerStructRet,
1490                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1491                                     const SmallVectorImpl<SDValue> &OutVals,
1492                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1493                                     SelectionDAG& DAG) const {
1494
1495   // For CallingConv::C this function knows whether the ABI needs
1496   // changing. That's not true for other conventions so they will have to opt in
1497   // manually.
1498   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1499     return false;
1500
1501   const MachineFunction &MF = DAG.getMachineFunction();
1502   const Function *CallerF = MF.getFunction();
1503   CallingConv::ID CallerCC = CallerF->getCallingConv();
1504   bool CCMatch = CallerCC == CalleeCC;
1505
1506   // Byval parameters hand the function a pointer directly into the stack area
1507   // we want to reuse during a tail call. Working around this *is* possible (see
1508   // X86) but less efficient and uglier in LowerCall.
1509   for (Function::const_arg_iterator i = CallerF->arg_begin(),
1510          e = CallerF->arg_end(); i != e; ++i)
1511     if (i->hasByValAttr())
1512       return false;
1513
1514   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
1515     if (IsTailCallConvention(CalleeCC) && CCMatch)
1516       return true;
1517     return false;
1518   }
1519
1520   // Now we search for cases where we can use a tail call without changing the
1521   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
1522   // concept.
1523
1524   // I want anyone implementing a new calling convention to think long and hard
1525   // about this assert.
1526   assert((!IsVarArg || CalleeCC == CallingConv::C)
1527          && "Unexpected variadic calling convention");
1528
1529   if (IsVarArg && !Outs.empty()) {
1530     // At least two cases here: if caller is fastcc then we can't have any
1531     // memory arguments (we'd be expected to clean up the stack afterwards). If
1532     // caller is C then we could potentially use its argument area.
1533
1534     // FIXME: for now we take the most conservative of these in both cases:
1535     // disallow all variadic memory operands.
1536     SmallVector<CCValAssign, 16> ArgLocs;
1537     CCState CCInfo(CalleeCC, IsVarArg, DAG.getMachineFunction(),
1538                    getTargetMachine(), ArgLocs, *DAG.getContext());
1539
1540     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
1541     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
1542       if (!ArgLocs[i].isRegLoc())
1543         return false;
1544   }
1545
1546   // If the calling conventions do not match, then we'd better make sure the
1547   // results are returned in the same way as what the caller expects.
1548   if (!CCMatch) {
1549     SmallVector<CCValAssign, 16> RVLocs1;
1550     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1551                     getTargetMachine(), RVLocs1, *DAG.getContext());
1552     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC));
1553
1554     SmallVector<CCValAssign, 16> RVLocs2;
1555     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1556                     getTargetMachine(), RVLocs2, *DAG.getContext());
1557     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC));
1558
1559     if (RVLocs1.size() != RVLocs2.size())
1560       return false;
1561     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1562       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1563         return false;
1564       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1565         return false;
1566       if (RVLocs1[i].isRegLoc()) {
1567         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1568           return false;
1569       } else {
1570         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1571           return false;
1572       }
1573     }
1574   }
1575
1576   // Nothing more to check if the callee is taking no arguments
1577   if (Outs.empty())
1578     return true;
1579
1580   SmallVector<CCValAssign, 16> ArgLocs;
1581   CCState CCInfo(CalleeCC, IsVarArg, DAG.getMachineFunction(),
1582                  getTargetMachine(), ArgLocs, *DAG.getContext());
1583
1584   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
1585
1586   const AArch64MachineFunctionInfo *FuncInfo
1587     = MF.getInfo<AArch64MachineFunctionInfo>();
1588
1589   // If the stack arguments for this call would fit into our own save area then
1590   // the call can be made tail.
1591   return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
1592 }
1593
1594 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
1595                                                    bool TailCallOpt) const {
1596   return CallCC == CallingConv::Fast && TailCallOpt;
1597 }
1598
1599 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
1600   return CallCC == CallingConv::Fast;
1601 }
1602
1603 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
1604                                                    SelectionDAG &DAG,
1605                                                    MachineFrameInfo *MFI,
1606                                                    int ClobberedFI) const {
1607   SmallVector<SDValue, 8> ArgChains;
1608   int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
1609   int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
1610
1611   // Include the original chain at the beginning of the list. When this is
1612   // used by target LowerCall hooks, this helps legalize find the
1613   // CALLSEQ_BEGIN node.
1614   ArgChains.push_back(Chain);
1615
1616   // Add a chain value for each stack argument corresponding
1617   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
1618          UE = DAG.getEntryNode().getNode()->use_end(); U != UE; ++U)
1619     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
1620       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
1621         if (FI->getIndex() < 0) {
1622           int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
1623           int64_t InLastByte = InFirstByte;
1624           InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
1625
1626           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
1627               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
1628             ArgChains.push_back(SDValue(L, 1));
1629         }
1630
1631    // Build a tokenfactor for all the chains.
1632    return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other,
1633                       &ArgChains[0], ArgChains.size());
1634 }
1635
1636 static A64CC::CondCodes IntCCToA64CC(ISD::CondCode CC) {
1637   switch (CC) {
1638   case ISD::SETEQ:  return A64CC::EQ;
1639   case ISD::SETGT:  return A64CC::GT;
1640   case ISD::SETGE:  return A64CC::GE;
1641   case ISD::SETLT:  return A64CC::LT;
1642   case ISD::SETLE:  return A64CC::LE;
1643   case ISD::SETNE:  return A64CC::NE;
1644   case ISD::SETUGT: return A64CC::HI;
1645   case ISD::SETUGE: return A64CC::HS;
1646   case ISD::SETULT: return A64CC::LO;
1647   case ISD::SETULE: return A64CC::LS;
1648   default: llvm_unreachable("Unexpected condition code");
1649   }
1650 }
1651
1652 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Val) const {
1653   // icmp is implemented using adds/subs immediate, which take an unsigned
1654   // 12-bit immediate, optionally shifted left by 12 bits.
1655
1656   // Symmetric by using adds/subs
1657   if (Val < 0)
1658     Val = -Val;
1659
1660   return (Val & ~0xfff) == 0 || (Val & ~0xfff000) == 0;
1661 }
1662
1663 SDValue AArch64TargetLowering::getSelectableIntSetCC(SDValue LHS, SDValue RHS,
1664                                         ISD::CondCode CC, SDValue &A64cc,
1665                                         SelectionDAG &DAG, SDLoc &dl) const {
1666   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1667     int64_t C = 0;
1668     EVT VT = RHSC->getValueType(0);
1669     bool knownInvalid = false;
1670
1671     // I'm not convinced the rest of LLVM handles these edge cases properly, but
1672     // we can at least get it right.
1673     if (isSignedIntSetCC(CC)) {
1674       C = RHSC->getSExtValue();
1675     } else if (RHSC->getZExtValue() > INT64_MAX) {
1676       // A 64-bit constant not representable by a signed 64-bit integer is far
1677       // too big to fit into a SUBS immediate anyway.
1678       knownInvalid = true;
1679     } else {
1680       C = RHSC->getZExtValue();
1681     }
1682
1683     if (!knownInvalid && !isLegalICmpImmediate(C)) {
1684       // Constant does not fit, try adjusting it by one?
1685       switch (CC) {
1686       default: break;
1687       case ISD::SETLT:
1688       case ISD::SETGE:
1689         if (isLegalICmpImmediate(C-1)) {
1690           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1691           RHS = DAG.getConstant(C-1, VT);
1692         }
1693         break;
1694       case ISD::SETULT:
1695       case ISD::SETUGE:
1696         if (isLegalICmpImmediate(C-1)) {
1697           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1698           RHS = DAG.getConstant(C-1, VT);
1699         }
1700         break;
1701       case ISD::SETLE:
1702       case ISD::SETGT:
1703         if (isLegalICmpImmediate(C+1)) {
1704           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1705           RHS = DAG.getConstant(C+1, VT);
1706         }
1707         break;
1708       case ISD::SETULE:
1709       case ISD::SETUGT:
1710         if (isLegalICmpImmediate(C+1)) {
1711           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1712           RHS = DAG.getConstant(C+1, VT);
1713         }
1714         break;
1715       }
1716     }
1717   }
1718
1719   A64CC::CondCodes CondCode = IntCCToA64CC(CC);
1720   A64cc = DAG.getConstant(CondCode, MVT::i32);
1721   return DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
1722                      DAG.getCondCode(CC));
1723 }
1724
1725 static A64CC::CondCodes FPCCToA64CC(ISD::CondCode CC,
1726                                     A64CC::CondCodes &Alternative) {
1727   A64CC::CondCodes CondCode = A64CC::Invalid;
1728   Alternative = A64CC::Invalid;
1729
1730   switch (CC) {
1731   default: llvm_unreachable("Unknown FP condition!");
1732   case ISD::SETEQ:
1733   case ISD::SETOEQ: CondCode = A64CC::EQ; break;
1734   case ISD::SETGT:
1735   case ISD::SETOGT: CondCode = A64CC::GT; break;
1736   case ISD::SETGE:
1737   case ISD::SETOGE: CondCode = A64CC::GE; break;
1738   case ISD::SETOLT: CondCode = A64CC::MI; break;
1739   case ISD::SETOLE: CondCode = A64CC::LS; break;
1740   case ISD::SETONE: CondCode = A64CC::MI; Alternative = A64CC::GT; break;
1741   case ISD::SETO:   CondCode = A64CC::VC; break;
1742   case ISD::SETUO:  CondCode = A64CC::VS; break;
1743   case ISD::SETUEQ: CondCode = A64CC::EQ; Alternative = A64CC::VS; break;
1744   case ISD::SETUGT: CondCode = A64CC::HI; break;
1745   case ISD::SETUGE: CondCode = A64CC::PL; break;
1746   case ISD::SETLT:
1747   case ISD::SETULT: CondCode = A64CC::LT; break;
1748   case ISD::SETLE:
1749   case ISD::SETULE: CondCode = A64CC::LE; break;
1750   case ISD::SETNE:
1751   case ISD::SETUNE: CondCode = A64CC::NE; break;
1752   }
1753   return CondCode;
1754 }
1755
1756 SDValue
1757 AArch64TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
1758   SDLoc DL(Op);
1759   EVT PtrVT = getPointerTy();
1760   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1761
1762   switch(getTargetMachine().getCodeModel()) {
1763   case CodeModel::Small:
1764     // The most efficient code is PC-relative anyway for the small memory model,
1765     // so we don't need to worry about relocation model.
1766     return DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
1767                        DAG.getTargetBlockAddress(BA, PtrVT, 0,
1768                                                  AArch64II::MO_NO_FLAG),
1769                        DAG.getTargetBlockAddress(BA, PtrVT, 0,
1770                                                  AArch64II::MO_LO12),
1771                        DAG.getConstant(/*Alignment=*/ 4, MVT::i32));
1772   case CodeModel::Large:
1773     return DAG.getNode(
1774       AArch64ISD::WrapperLarge, DL, PtrVT,
1775       DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G3),
1776       DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G2_NC),
1777       DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G1_NC),
1778       DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_ABS_G0_NC));
1779   default:
1780     llvm_unreachable("Only small and large code models supported now");
1781   }
1782 }
1783
1784
1785 // (BRCOND chain, val, dest)
1786 SDValue
1787 AArch64TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1788   SDLoc dl(Op);
1789   SDValue Chain = Op.getOperand(0);
1790   SDValue TheBit = Op.getOperand(1);
1791   SDValue DestBB = Op.getOperand(2);
1792
1793   // AArch64 BooleanContents is the default UndefinedBooleanContent, which means
1794   // that as the consumer we are responsible for ignoring rubbish in higher
1795   // bits.
1796   TheBit = DAG.getNode(ISD::AND, dl, MVT::i32, TheBit,
1797                        DAG.getConstant(1, MVT::i32));
1798
1799   SDValue A64CMP = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, TheBit,
1800                                DAG.getConstant(0, TheBit.getValueType()),
1801                                DAG.getCondCode(ISD::SETNE));
1802
1803   return DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other, Chain,
1804                      A64CMP, DAG.getConstant(A64CC::NE, MVT::i32),
1805                      DestBB);
1806 }
1807
1808 // (BR_CC chain, condcode, lhs, rhs, dest)
1809 SDValue
1810 AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
1811   SDLoc dl(Op);
1812   SDValue Chain = Op.getOperand(0);
1813   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1814   SDValue LHS = Op.getOperand(2);
1815   SDValue RHS = Op.getOperand(3);
1816   SDValue DestBB = Op.getOperand(4);
1817
1818   if (LHS.getValueType() == MVT::f128) {
1819     // f128 comparisons are lowered to runtime calls by a routine which sets
1820     // LHS, RHS and CC appropriately for the rest of this function to continue.
1821     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
1822
1823     // If softenSetCCOperands returned a scalar, we need to compare the result
1824     // against zero to select between true and false values.
1825     if (RHS.getNode() == 0) {
1826       RHS = DAG.getConstant(0, LHS.getValueType());
1827       CC = ISD::SETNE;
1828     }
1829   }
1830
1831   if (LHS.getValueType().isInteger()) {
1832     SDValue A64cc;
1833
1834     // Integers are handled in a separate function because the combinations of
1835     // immediates and tests can get hairy and we may want to fiddle things.
1836     SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
1837
1838     return DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
1839                        Chain, CmpOp, A64cc, DestBB);
1840   }
1841
1842   // Note that some LLVM floating-point CondCodes can't be lowered to a single
1843   // conditional branch, hence FPCCToA64CC can set a second test, where either
1844   // passing is sufficient.
1845   A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
1846   CondCode = FPCCToA64CC(CC, Alternative);
1847   SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
1848   SDValue SetCC = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
1849                               DAG.getCondCode(CC));
1850   SDValue A64BR_CC = DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
1851                                  Chain, SetCC, A64cc, DestBB);
1852
1853   if (Alternative != A64CC::Invalid) {
1854     A64cc = DAG.getConstant(Alternative, MVT::i32);
1855     A64BR_CC = DAG.getNode(AArch64ISD::BR_CC, dl, MVT::Other,
1856                            A64BR_CC, SetCC, A64cc, DestBB);
1857
1858   }
1859
1860   return A64BR_CC;
1861 }
1862
1863 SDValue
1864 AArch64TargetLowering::LowerF128ToCall(SDValue Op, SelectionDAG &DAG,
1865                                        RTLIB::Libcall Call) const {
1866   ArgListTy Args;
1867   ArgListEntry Entry;
1868   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
1869     EVT ArgVT = Op.getOperand(i).getValueType();
1870     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1871     Entry.Node = Op.getOperand(i); Entry.Ty = ArgTy;
1872     Entry.isSExt = false;
1873     Entry.isZExt = false;
1874     Args.push_back(Entry);
1875   }
1876   SDValue Callee = DAG.getExternalSymbol(getLibcallName(Call), getPointerTy());
1877
1878   Type *RetTy = Op.getValueType().getTypeForEVT(*DAG.getContext());
1879
1880   // By default, the input chain to this libcall is the entry node of the
1881   // function. If the libcall is going to be emitted as a tail call then
1882   // isUsedByReturnOnly will change it to the right chain if the return
1883   // node which is being folded has a non-entry input chain.
1884   SDValue InChain = DAG.getEntryNode();
1885
1886   // isTailCall may be true since the callee does not reference caller stack
1887   // frame. Check if it's in the right position.
1888   SDValue TCChain = InChain;
1889   bool isTailCall = isInTailCallPosition(DAG, Op.getNode(), TCChain);
1890   if (isTailCall)
1891     InChain = TCChain;
1892
1893   TargetLowering::
1894   CallLoweringInfo CLI(InChain, RetTy, false, false, false, false,
1895                     0, getLibcallCallingConv(Call), isTailCall,
1896                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
1897                     Callee, Args, DAG, SDLoc(Op));
1898   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
1899
1900   if (!CallInfo.second.getNode())
1901     // It's a tailcall, return the chain (which is the DAG root).
1902     return DAG.getRoot();
1903
1904   return CallInfo.first;
1905 }
1906
1907 SDValue
1908 AArch64TargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
1909   if (Op.getOperand(0).getValueType() != MVT::f128) {
1910     // It's legal except when f128 is involved
1911     return Op;
1912   }
1913
1914   RTLIB::Libcall LC;
1915   LC  = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1916
1917   SDValue SrcVal = Op.getOperand(0);
1918   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1919                      /*isSigned*/ false, SDLoc(Op)).first;
1920 }
1921
1922 SDValue
1923 AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
1924   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1925
1926   RTLIB::Libcall LC;
1927   LC  = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1928
1929   return LowerF128ToCall(Op, DAG, LC);
1930 }
1931
1932 SDValue
1933 AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
1934                                       bool IsSigned) const {
1935   if (Op.getOperand(0).getValueType() != MVT::f128) {
1936     // It's legal except when f128 is involved
1937     return Op;
1938   }
1939
1940   RTLIB::Libcall LC;
1941   if (IsSigned)
1942     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1943   else
1944     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1945
1946   return LowerF128ToCall(Op, DAG, LC);
1947 }
1948
1949 SDValue
1950 AArch64TargetLowering::LowerGlobalAddressELFLarge(SDValue Op,
1951                                                   SelectionDAG &DAG) const {
1952   assert(getTargetMachine().getCodeModel() == CodeModel::Large);
1953   assert(getTargetMachine().getRelocationModel() == Reloc::Static);
1954
1955   EVT PtrVT = getPointerTy();
1956   SDLoc dl(Op);
1957   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
1958   const GlobalValue *GV = GN->getGlobal();
1959
1960   SDValue GlobalAddr = DAG.getNode(
1961       AArch64ISD::WrapperLarge, dl, PtrVT,
1962       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G3),
1963       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G2_NC),
1964       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G1_NC),
1965       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, AArch64II::MO_ABS_G0_NC));
1966
1967   if (GN->getOffset() != 0)
1968     return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalAddr,
1969                        DAG.getConstant(GN->getOffset(), PtrVT));
1970
1971   return GlobalAddr;
1972 }
1973
1974 SDValue
1975 AArch64TargetLowering::LowerGlobalAddressELFSmall(SDValue Op,
1976                                                   SelectionDAG &DAG) const {
1977   assert(getTargetMachine().getCodeModel() == CodeModel::Small);
1978
1979   EVT PtrVT = getPointerTy();
1980   SDLoc dl(Op);
1981   const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
1982   const GlobalValue *GV = GN->getGlobal();
1983   unsigned Alignment = GV->getAlignment();
1984   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
1985   if (GV->isWeakForLinker() && GV->isDeclaration() && RelocM == Reloc::Static) {
1986     // Weak undefined symbols can't use ADRP/ADD pair since they should evaluate
1987     // to zero when they remain undefined. In PIC mode the GOT can take care of
1988     // this, but in absolute mode we use a constant pool load.
1989     SDValue PoolAddr;
1990     PoolAddr = DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
1991                            DAG.getTargetConstantPool(GV, PtrVT, 0, 0,
1992                                                      AArch64II::MO_NO_FLAG),
1993                            DAG.getTargetConstantPool(GV, PtrVT, 0, 0,
1994                                                      AArch64II::MO_LO12),
1995                            DAG.getConstant(8, MVT::i32));
1996     SDValue GlobalAddr = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), PoolAddr,
1997                                      MachinePointerInfo::getConstantPool(),
1998                                      /*isVolatile=*/ false,
1999                                      /*isNonTemporal=*/ true,
2000                                      /*isInvariant=*/ true, 8);
2001     if (GN->getOffset() != 0)
2002       return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalAddr,
2003                          DAG.getConstant(GN->getOffset(), PtrVT));
2004
2005     return GlobalAddr;
2006   }
2007
2008   if (Alignment == 0) {
2009     const PointerType *GVPtrTy = cast<PointerType>(GV->getType());
2010     if (GVPtrTy->getElementType()->isSized()) {
2011       Alignment
2012         = getDataLayout()->getABITypeAlignment(GVPtrTy->getElementType());
2013     } else {
2014       // Be conservative if we can't guess, not that it really matters:
2015       // functions and labels aren't valid for loads, and the methods used to
2016       // actually calculate an address work with any alignment.
2017       Alignment = 1;
2018     }
2019   }
2020
2021   unsigned char HiFixup, LoFixup;
2022   bool UseGOT = getSubtarget()->GVIsIndirectSymbol(GV, RelocM);
2023
2024   if (UseGOT) {
2025     HiFixup = AArch64II::MO_GOT;
2026     LoFixup = AArch64II::MO_GOT_LO12;
2027     Alignment = 8;
2028   } else {
2029     HiFixup = AArch64II::MO_NO_FLAG;
2030     LoFixup = AArch64II::MO_LO12;
2031   }
2032
2033   // AArch64's small model demands the following sequence:
2034   // ADRP x0, somewhere
2035   // ADD x0, x0, #:lo12:somewhere ; (or LDR directly).
2036   SDValue GlobalRef = DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2037                                   DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2038                                                              HiFixup),
2039                                   DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2040                                                              LoFixup),
2041                                   DAG.getConstant(Alignment, MVT::i32));
2042
2043   if (UseGOT) {
2044     GlobalRef = DAG.getNode(AArch64ISD::GOTLoad, dl, PtrVT, DAG.getEntryNode(),
2045                             GlobalRef);
2046   }
2047
2048   if (GN->getOffset() != 0)
2049     return DAG.getNode(ISD::ADD, dl, PtrVT, GlobalRef,
2050                        DAG.getConstant(GN->getOffset(), PtrVT));
2051
2052   return GlobalRef;
2053 }
2054
2055 SDValue
2056 AArch64TargetLowering::LowerGlobalAddressELF(SDValue Op,
2057                                              SelectionDAG &DAG) const {
2058   // TableGen doesn't have easy access to the CodeModel or RelocationModel, so
2059   // we make those distinctions here.
2060
2061   switch (getTargetMachine().getCodeModel()) {
2062   case CodeModel::Small:
2063     return LowerGlobalAddressELFSmall(Op, DAG);
2064   case CodeModel::Large:
2065     return LowerGlobalAddressELFLarge(Op, DAG);
2066   default:
2067     llvm_unreachable("Only small and large code models supported now");
2068   }
2069 }
2070
2071 SDValue AArch64TargetLowering::LowerTLSDescCall(SDValue SymAddr,
2072                                                 SDValue DescAddr,
2073                                                 SDLoc DL,
2074                                                 SelectionDAG &DAG) const {
2075   EVT PtrVT = getPointerTy();
2076
2077   // The function we need to call is simply the first entry in the GOT for this
2078   // descriptor, load it in preparation.
2079   SDValue Func, Chain;
2080   Func = DAG.getNode(AArch64ISD::GOTLoad, DL, PtrVT, DAG.getEntryNode(),
2081                      DescAddr);
2082
2083   // The function takes only one argument: the address of the descriptor itself
2084   // in X0.
2085   SDValue Glue;
2086   Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::X0, DescAddr, Glue);
2087   Glue = Chain.getValue(1);
2088
2089   // Finally, there's a special calling-convention which means that the lookup
2090   // must preserve all registers (except X0, obviously).
2091   const TargetRegisterInfo *TRI  = getTargetMachine().getRegisterInfo();
2092   const AArch64RegisterInfo *A64RI
2093     = static_cast<const AArch64RegisterInfo *>(TRI);
2094   const uint32_t *Mask = A64RI->getTLSDescCallPreservedMask();
2095
2096   // We're now ready to populate the argument list, as with a normal call:
2097   std::vector<SDValue> Ops;
2098   Ops.push_back(Chain);
2099   Ops.push_back(Func);
2100   Ops.push_back(SymAddr);
2101   Ops.push_back(DAG.getRegister(AArch64::X0, PtrVT));
2102   Ops.push_back(DAG.getRegisterMask(Mask));
2103   Ops.push_back(Glue);
2104
2105   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2106   Chain = DAG.getNode(AArch64ISD::TLSDESCCALL, DL, NodeTys, &Ops[0],
2107                       Ops.size());
2108   Glue = Chain.getValue(1);
2109
2110   // After the call, the offset from TPIDR_EL0 is in X0, copy it out and pass it
2111   // back to the generic handling code.
2112   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
2113 }
2114
2115 SDValue
2116 AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2117                                              SelectionDAG &DAG) const {
2118   assert(getSubtarget()->isTargetELF() &&
2119          "TLS not implemented for non-ELF targets");
2120   assert(getTargetMachine().getCodeModel() == CodeModel::Small
2121          && "TLS only supported in small memory model");
2122   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2123
2124   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2125
2126   SDValue TPOff;
2127   EVT PtrVT = getPointerTy();
2128   SDLoc DL(Op);
2129   const GlobalValue *GV = GA->getGlobal();
2130
2131   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
2132
2133   if (Model == TLSModel::InitialExec) {
2134     TPOff = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2135                         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2136                                                    AArch64II::MO_GOTTPREL),
2137                         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2138                                                    AArch64II::MO_GOTTPREL_LO12),
2139                         DAG.getConstant(8, MVT::i32));
2140     TPOff = DAG.getNode(AArch64ISD::GOTLoad, DL, PtrVT, DAG.getEntryNode(),
2141                         TPOff);
2142   } else if (Model == TLSModel::LocalExec) {
2143     SDValue HiVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2144                                                AArch64II::MO_TPREL_G1);
2145     SDValue LoVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2146                                                AArch64II::MO_TPREL_G0_NC);
2147
2148     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZxii, DL, PtrVT, HiVar,
2149                                        DAG.getTargetConstant(1, MVT::i32)), 0);
2150     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKxii, DL, PtrVT,
2151                                        TPOff, LoVar,
2152                                        DAG.getTargetConstant(0, MVT::i32)), 0);
2153   } else if (Model == TLSModel::GeneralDynamic) {
2154     // Accesses used in this sequence go via the TLS descriptor which lives in
2155     // the GOT. Prepare an address we can use to handle this.
2156     SDValue HiDesc = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2157                                                 AArch64II::MO_TLSDESC);
2158     SDValue LoDesc = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2159                                                 AArch64II::MO_TLSDESC_LO12);
2160     SDValue DescAddr = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2161                                    HiDesc, LoDesc,
2162                                    DAG.getConstant(8, MVT::i32));
2163     SDValue SymAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0);
2164
2165     TPOff = LowerTLSDescCall(SymAddr, DescAddr, DL, DAG);
2166   } else if (Model == TLSModel::LocalDynamic) {
2167     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2168     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2169     // the beginning of the module's TLS region, followed by a DTPREL offset
2170     // calculation.
2171
2172     // These accesses will need deduplicating if there's more than one.
2173     AArch64MachineFunctionInfo* MFI = DAG.getMachineFunction()
2174       .getInfo<AArch64MachineFunctionInfo>();
2175     MFI->incNumLocalDynamicTLSAccesses();
2176
2177
2178     // Get the location of _TLS_MODULE_BASE_:
2179     SDValue HiDesc = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2180                                                 AArch64II::MO_TLSDESC);
2181     SDValue LoDesc = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2182                                                 AArch64II::MO_TLSDESC_LO12);
2183     SDValue DescAddr = DAG.getNode(AArch64ISD::WrapperSmall, DL, PtrVT,
2184                                    HiDesc, LoDesc,
2185                                    DAG.getConstant(8, MVT::i32));
2186     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT);
2187
2188     ThreadBase = LowerTLSDescCall(SymAddr, DescAddr, DL, DAG);
2189
2190     // Get the variable's offset from _TLS_MODULE_BASE_
2191     SDValue HiVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2192                                                AArch64II::MO_DTPREL_G1);
2193     SDValue LoVar = DAG.getTargetGlobalAddress(GV, DL, MVT::i64, 0,
2194                                                AArch64II::MO_DTPREL_G0_NC);
2195
2196     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZxii, DL, PtrVT, HiVar,
2197                                        DAG.getTargetConstant(0, MVT::i32)), 0);
2198     TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKxii, DL, PtrVT,
2199                                        TPOff, LoVar,
2200                                        DAG.getTargetConstant(0, MVT::i32)), 0);
2201   } else
2202       llvm_unreachable("Unsupported TLS access model");
2203
2204
2205   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2206 }
2207
2208 SDValue
2209 AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG,
2210                                       bool IsSigned) const {
2211   if (Op.getValueType() != MVT::f128) {
2212     // Legal for everything except f128.
2213     return Op;
2214   }
2215
2216   RTLIB::Libcall LC;
2217   if (IsSigned)
2218     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2219   else
2220     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2221
2222   return LowerF128ToCall(Op, DAG, LC);
2223 }
2224
2225
2226 SDValue
2227 AArch64TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2228   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2229   SDLoc dl(JT);
2230   EVT PtrVT = getPointerTy();
2231
2232   // When compiling PIC, jump tables get put in the code section so a static
2233   // relocation-style is acceptable for both cases.
2234   switch (getTargetMachine().getCodeModel()) {
2235   case CodeModel::Small:
2236     return DAG.getNode(AArch64ISD::WrapperSmall, dl, PtrVT,
2237                        DAG.getTargetJumpTable(JT->getIndex(), PtrVT),
2238                        DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2239                                               AArch64II::MO_LO12),
2240                        DAG.getConstant(1, MVT::i32));
2241   case CodeModel::Large:
2242     return DAG.getNode(
2243       AArch64ISD::WrapperLarge, dl, PtrVT,
2244       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G3),
2245       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G2_NC),
2246       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G1_NC),
2247       DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_ABS_G0_NC));
2248   default:
2249     llvm_unreachable("Only small and large code models supported now");
2250   }
2251 }
2252
2253 // (SELECT_CC lhs, rhs, iftrue, iffalse, condcode)
2254 SDValue
2255 AArch64TargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2256   SDLoc dl(Op);
2257   SDValue LHS = Op.getOperand(0);
2258   SDValue RHS = Op.getOperand(1);
2259   SDValue IfTrue = Op.getOperand(2);
2260   SDValue IfFalse = Op.getOperand(3);
2261   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2262
2263   if (LHS.getValueType() == MVT::f128) {
2264     // f128 comparisons are lowered to libcalls, but slot in nicely here
2265     // afterwards.
2266     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2267
2268     // If softenSetCCOperands returned a scalar, we need to compare the result
2269     // against zero to select between true and false values.
2270     if (RHS.getNode() == 0) {
2271       RHS = DAG.getConstant(0, LHS.getValueType());
2272       CC = ISD::SETNE;
2273     }
2274   }
2275
2276   if (LHS.getValueType().isInteger()) {
2277     SDValue A64cc;
2278
2279     // Integers are handled in a separate function because the combinations of
2280     // immediates and tests can get hairy and we may want to fiddle things.
2281     SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
2282
2283     return DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2284                        CmpOp, IfTrue, IfFalse, A64cc);
2285   }
2286
2287   // Note that some LLVM floating-point CondCodes can't be lowered to a single
2288   // conditional branch, hence FPCCToA64CC can set a second test, where either
2289   // passing is sufficient.
2290   A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
2291   CondCode = FPCCToA64CC(CC, Alternative);
2292   SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
2293   SDValue SetCC = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
2294                               DAG.getCondCode(CC));
2295   SDValue A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl,
2296                                      Op.getValueType(),
2297                                      SetCC, IfTrue, IfFalse, A64cc);
2298
2299   if (Alternative != A64CC::Invalid) {
2300     A64cc = DAG.getConstant(Alternative, MVT::i32);
2301     A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2302                                SetCC, IfTrue, A64SELECT_CC, A64cc);
2303
2304   }
2305
2306   return A64SELECT_CC;
2307 }
2308
2309 // (SELECT testbit, iftrue, iffalse)
2310 SDValue
2311 AArch64TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2312   SDLoc dl(Op);
2313   SDValue TheBit = Op.getOperand(0);
2314   SDValue IfTrue = Op.getOperand(1);
2315   SDValue IfFalse = Op.getOperand(2);
2316
2317   // AArch64 BooleanContents is the default UndefinedBooleanContent, which means
2318   // that as the consumer we are responsible for ignoring rubbish in higher
2319   // bits.
2320   TheBit = DAG.getNode(ISD::AND, dl, MVT::i32, TheBit,
2321                        DAG.getConstant(1, MVT::i32));
2322   SDValue A64CMP = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, TheBit,
2323                                DAG.getConstant(0, TheBit.getValueType()),
2324                                DAG.getCondCode(ISD::SETNE));
2325
2326   return DAG.getNode(AArch64ISD::SELECT_CC, dl, Op.getValueType(),
2327                      A64CMP, IfTrue, IfFalse,
2328                      DAG.getConstant(A64CC::NE, MVT::i32));
2329 }
2330
2331 static SDValue LowerVectorSETCC(SDValue Op, SelectionDAG &DAG) {
2332   SDLoc DL(Op);
2333   SDValue LHS = Op.getOperand(0);
2334   SDValue RHS = Op.getOperand(1);
2335   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2336   EVT VT = Op.getValueType();
2337   bool Invert = false;
2338   SDValue Op0, Op1;
2339   unsigned Opcode;
2340
2341   if (LHS.getValueType().isInteger()) {
2342
2343     // Attempt to use Vector Integer Compare Mask Test instruction.
2344     // TST = icmp ne (and (op0, op1), zero).
2345     if (CC == ISD::SETNE) {
2346       if (((LHS.getOpcode() == ISD::AND) &&
2347            ISD::isBuildVectorAllZeros(RHS.getNode())) ||
2348           ((RHS.getOpcode() == ISD::AND) &&
2349            ISD::isBuildVectorAllZeros(LHS.getNode()))) {
2350
2351         SDValue AndOp = (LHS.getOpcode() == ISD::AND) ? LHS : RHS;
2352         SDValue NewLHS = DAG.getNode(ISD::BITCAST, DL, VT, AndOp.getOperand(0));
2353         SDValue NewRHS = DAG.getNode(ISD::BITCAST, DL, VT, AndOp.getOperand(1));
2354         return DAG.getNode(AArch64ISD::NEON_TST, DL, VT, NewLHS, NewRHS);
2355       }
2356     }
2357
2358     // Attempt to use Vector Integer Compare Mask against Zero instr (Signed).
2359     // Note: Compare against Zero does not support unsigned predicates.
2360     if ((ISD::isBuildVectorAllZeros(RHS.getNode()) ||
2361          ISD::isBuildVectorAllZeros(LHS.getNode())) &&
2362         !isUnsignedIntSetCC(CC)) {
2363
2364       // If LHS is the zero value, swap operands and CondCode.
2365       if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
2366         CC = getSetCCSwappedOperands(CC);
2367         Op0 = RHS;
2368       } else
2369         Op0 = LHS;
2370
2371       // Ensure valid CondCode for Compare Mask against Zero instruction:
2372       // EQ, GE, GT, LE, LT.
2373       if (ISD::SETNE == CC) {
2374         Invert = true;
2375         CC = ISD::SETEQ;
2376       }
2377
2378       // Using constant type to differentiate integer and FP compares with zero.
2379       Op1 = DAG.getConstant(0, MVT::i32);
2380       Opcode = AArch64ISD::NEON_CMPZ;
2381
2382     } else {
2383       // Attempt to use Vector Integer Compare Mask instr (Signed/Unsigned).
2384       // Ensure valid CondCode for Compare Mask instr: EQ, GE, GT, UGE, UGT.
2385       bool Swap = false;
2386       switch (CC) {
2387       default:
2388         llvm_unreachable("Illegal integer comparison.");
2389       case ISD::SETEQ:
2390       case ISD::SETGT:
2391       case ISD::SETGE:
2392       case ISD::SETUGT:
2393       case ISD::SETUGE:
2394         break;
2395       case ISD::SETNE:
2396         Invert = true;
2397         CC = ISD::SETEQ;
2398         break;
2399       case ISD::SETULT:
2400       case ISD::SETULE:
2401       case ISD::SETLT:
2402       case ISD::SETLE:
2403         Swap = true;
2404         CC = getSetCCSwappedOperands(CC);
2405       }
2406
2407       if (Swap)
2408         std::swap(LHS, RHS);
2409
2410       Opcode = AArch64ISD::NEON_CMP;
2411       Op0 = LHS;
2412       Op1 = RHS;
2413     }
2414
2415     // Generate Compare Mask instr or Compare Mask against Zero instr.
2416     SDValue NeonCmp =
2417         DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(CC));
2418
2419     if (Invert)
2420       NeonCmp = DAG.getNOT(DL, NeonCmp, VT);
2421
2422     return NeonCmp;
2423   }
2424
2425   // Now handle Floating Point cases.
2426   // Attempt to use Vector Floating Point Compare Mask against Zero instruction.
2427   if (ISD::isBuildVectorAllZeros(RHS.getNode()) ||
2428       ISD::isBuildVectorAllZeros(LHS.getNode())) {
2429
2430     // If LHS is the zero value, swap operands and CondCode.
2431     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
2432       CC = getSetCCSwappedOperands(CC);
2433       Op0 = RHS;
2434     } else
2435       Op0 = LHS;
2436
2437     // Using constant type to differentiate integer and FP compares with zero.
2438     Op1 = DAG.getConstantFP(0, MVT::f32);
2439     Opcode = AArch64ISD::NEON_CMPZ;
2440   } else {
2441     // Attempt to use Vector Floating Point Compare Mask instruction.
2442     Op0 = LHS;
2443     Op1 = RHS;
2444     Opcode = AArch64ISD::NEON_CMP;
2445   }
2446
2447   SDValue NeonCmpAlt;
2448   // Some register compares have to be implemented with swapped CC and operands,
2449   // e.g.: OLT implemented as OGT with swapped operands.
2450   bool SwapIfRegArgs = false;
2451
2452   // Ensure valid CondCode for FP Compare Mask against Zero instruction:
2453   // EQ, GE, GT, LE, LT.
2454   // And ensure valid CondCode for FP Compare Mask instruction: EQ, GE, GT.
2455   switch (CC) {
2456   default:
2457     llvm_unreachable("Illegal FP comparison");
2458   case ISD::SETUNE:
2459   case ISD::SETNE:
2460     Invert = true; // Fallthrough
2461   case ISD::SETOEQ:
2462   case ISD::SETEQ:
2463     CC = ISD::SETEQ;
2464     break;
2465   case ISD::SETOLT:
2466   case ISD::SETLT:
2467     CC = ISD::SETLT;
2468     SwapIfRegArgs = true;
2469     break;
2470   case ISD::SETOGT:
2471   case ISD::SETGT:
2472     CC = ISD::SETGT;
2473     break;
2474   case ISD::SETOLE:
2475   case ISD::SETLE:
2476     CC = ISD::SETLE;
2477     SwapIfRegArgs = true;
2478     break;
2479   case ISD::SETOGE:
2480   case ISD::SETGE:
2481     CC = ISD::SETGE;
2482     break;
2483   case ISD::SETUGE:
2484     Invert = true;
2485     CC = ISD::SETLT;
2486     SwapIfRegArgs = true;
2487     break;
2488   case ISD::SETULE:
2489     Invert = true;
2490     CC = ISD::SETGT;
2491     break;
2492   case ISD::SETUGT:
2493     Invert = true;
2494     CC = ISD::SETLE;
2495     SwapIfRegArgs = true;
2496     break;
2497   case ISD::SETULT:
2498     Invert = true;
2499     CC = ISD::SETGE;
2500     break;
2501   case ISD::SETUEQ:
2502     Invert = true; // Fallthrough
2503   case ISD::SETONE:
2504     // Expand this to (OGT |OLT).
2505     NeonCmpAlt =
2506         DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(ISD::SETGT));
2507     CC = ISD::SETLT;
2508     SwapIfRegArgs = true;
2509     break;
2510   case ISD::SETUO:
2511     Invert = true; // Fallthrough
2512   case ISD::SETO:
2513     // Expand this to (OGE | OLT).
2514     NeonCmpAlt =
2515         DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(ISD::SETGE));
2516     CC = ISD::SETLT;
2517     SwapIfRegArgs = true;
2518     break;
2519   }
2520
2521   if (Opcode == AArch64ISD::NEON_CMP && SwapIfRegArgs) {
2522     CC = getSetCCSwappedOperands(CC);
2523     std::swap(Op0, Op1);
2524   }
2525
2526   // Generate FP Compare Mask instr or FP Compare Mask against Zero instr
2527   SDValue NeonCmp = DAG.getNode(Opcode, DL, VT, Op0, Op1, DAG.getCondCode(CC));
2528
2529   if (NeonCmpAlt.getNode())
2530     NeonCmp = DAG.getNode(ISD::OR, DL, VT, NeonCmp, NeonCmpAlt);
2531
2532   if (Invert)
2533     NeonCmp = DAG.getNOT(DL, NeonCmp, VT);
2534
2535   return NeonCmp;
2536 }
2537
2538 // (SETCC lhs, rhs, condcode)
2539 SDValue
2540 AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2541   SDLoc dl(Op);
2542   SDValue LHS = Op.getOperand(0);
2543   SDValue RHS = Op.getOperand(1);
2544   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2545   EVT VT = Op.getValueType();
2546
2547   if (VT.isVector())
2548     return LowerVectorSETCC(Op, DAG);
2549
2550   if (LHS.getValueType() == MVT::f128) {
2551     // f128 comparisons will be lowered to libcalls giving a valid LHS and RHS
2552     // for the rest of the function (some i32 or i64 values).
2553     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2554
2555     // If softenSetCCOperands returned a scalar, use it.
2556     if (RHS.getNode() == 0) {
2557       assert(LHS.getValueType() == Op.getValueType() &&
2558              "Unexpected setcc expansion!");
2559       return LHS;
2560     }
2561   }
2562
2563   if (LHS.getValueType().isInteger()) {
2564     SDValue A64cc;
2565
2566     // Integers are handled in a separate function because the combinations of
2567     // immediates and tests can get hairy and we may want to fiddle things.
2568     SDValue CmpOp = getSelectableIntSetCC(LHS, RHS, CC, A64cc, DAG, dl);
2569
2570     return DAG.getNode(AArch64ISD::SELECT_CC, dl, VT,
2571                        CmpOp, DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2572                        A64cc);
2573   }
2574
2575   // Note that some LLVM floating-point CondCodes can't be lowered to a single
2576   // conditional branch, hence FPCCToA64CC can set a second test, where either
2577   // passing is sufficient.
2578   A64CC::CondCodes CondCode, Alternative = A64CC::Invalid;
2579   CondCode = FPCCToA64CC(CC, Alternative);
2580   SDValue A64cc = DAG.getConstant(CondCode, MVT::i32);
2581   SDValue CmpOp = DAG.getNode(AArch64ISD::SETCC, dl, MVT::i32, LHS, RHS,
2582                               DAG.getCondCode(CC));
2583   SDValue A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT,
2584                                      CmpOp, DAG.getConstant(1, VT),
2585                                      DAG.getConstant(0, VT), A64cc);
2586
2587   if (Alternative != A64CC::Invalid) {
2588     A64cc = DAG.getConstant(Alternative, MVT::i32);
2589     A64SELECT_CC = DAG.getNode(AArch64ISD::SELECT_CC, dl, VT, CmpOp,
2590                                DAG.getConstant(1, VT), A64SELECT_CC, A64cc);
2591   }
2592
2593   return A64SELECT_CC;
2594 }
2595
2596 SDValue
2597 AArch64TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2598   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2599   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
2600
2601   // We have to make sure we copy the entire structure: 8+8+8+4+4 = 32 bytes
2602   // rather than just 8.
2603   return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op),
2604                        Op.getOperand(1), Op.getOperand(2),
2605                        DAG.getConstant(32, MVT::i32), 8, false, false,
2606                        MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
2607 }
2608
2609 SDValue
2610 AArch64TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2611   // The layout of the va_list struct is specified in the AArch64 Procedure Call
2612   // Standard, section B.3.
2613   MachineFunction &MF = DAG.getMachineFunction();
2614   AArch64MachineFunctionInfo *FuncInfo
2615     = MF.getInfo<AArch64MachineFunctionInfo>();
2616   SDLoc DL(Op);
2617
2618   SDValue Chain = Op.getOperand(0);
2619   SDValue VAList = Op.getOperand(1);
2620   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2621   SmallVector<SDValue, 4> MemOps;
2622
2623   // void *__stack at offset 0
2624   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVariadicStackIdx(),
2625                                     getPointerTy());
2626   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
2627                                 MachinePointerInfo(SV), false, false, 0));
2628
2629   // void *__gr_top at offset 8
2630   int GPRSize = FuncInfo->getVariadicGPRSize();
2631   if (GPRSize > 0) {
2632     SDValue GRTop, GRTopAddr;
2633
2634     GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2635                             DAG.getConstant(8, getPointerTy()));
2636
2637     GRTop = DAG.getFrameIndex(FuncInfo->getVariadicGPRIdx(), getPointerTy());
2638     GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
2639                         DAG.getConstant(GPRSize, getPointerTy()));
2640
2641     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
2642                                   MachinePointerInfo(SV, 8),
2643                                   false, false, 0));
2644   }
2645
2646   // void *__vr_top at offset 16
2647   int FPRSize = FuncInfo->getVariadicFPRSize();
2648   if (FPRSize > 0) {
2649     SDValue VRTop, VRTopAddr;
2650     VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2651                             DAG.getConstant(16, getPointerTy()));
2652
2653     VRTop = DAG.getFrameIndex(FuncInfo->getVariadicFPRIdx(), getPointerTy());
2654     VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
2655                         DAG.getConstant(FPRSize, getPointerTy()));
2656
2657     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
2658                                   MachinePointerInfo(SV, 16),
2659                                   false, false, 0));
2660   }
2661
2662   // int __gr_offs at offset 24
2663   SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2664                                    DAG.getConstant(24, getPointerTy()));
2665   MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
2666                                 GROffsAddr, MachinePointerInfo(SV, 24),
2667                                 false, false, 0));
2668
2669   // int __vr_offs at offset 28
2670   SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
2671                                    DAG.getConstant(28, getPointerTy()));
2672   MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
2673                                 VROffsAddr, MachinePointerInfo(SV, 28),
2674                                 false, false, 0));
2675
2676   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
2677                      MemOps.size());
2678 }
2679
2680 SDValue
2681 AArch64TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
2682   switch (Op.getOpcode()) {
2683   default: llvm_unreachable("Don't know how to custom lower this!");
2684   case ISD::FADD: return LowerF128ToCall(Op, DAG, RTLIB::ADD_F128);
2685   case ISD::FSUB: return LowerF128ToCall(Op, DAG, RTLIB::SUB_F128);
2686   case ISD::FMUL: return LowerF128ToCall(Op, DAG, RTLIB::MUL_F128);
2687   case ISD::FDIV: return LowerF128ToCall(Op, DAG, RTLIB::DIV_F128);
2688   case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, true);
2689   case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG, false);
2690   case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG, true);
2691   case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG, false);
2692   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
2693   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
2694
2695   case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
2696   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
2697   case ISD::BR_CC: return LowerBR_CC(Op, DAG);
2698   case ISD::GlobalAddress: return LowerGlobalAddressELF(Op, DAG);
2699   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
2700   case ISD::JumpTable: return LowerJumpTable(Op, DAG);
2701   case ISD::SELECT: return LowerSELECT(Op, DAG);
2702   case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
2703   case ISD::SETCC: return LowerSETCC(Op, DAG);
2704   case ISD::VACOPY: return LowerVACOPY(Op, DAG);
2705   case ISD::VASTART: return LowerVASTART(Op, DAG);
2706   case ISD::BUILD_VECTOR:
2707     return LowerBUILD_VECTOR(Op, DAG, getSubtarget());
2708   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
2709   }
2710
2711   return SDValue();
2712 }
2713
2714 /// Check if the specified splat value corresponds to a valid vector constant
2715 /// for a Neon instruction with a "modified immediate" operand (e.g., MOVI).  If
2716 /// so, return the encoded 8-bit immediate and the OpCmode instruction fields
2717 /// values.
2718 static bool isNeonModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
2719                               unsigned SplatBitSize, SelectionDAG &DAG,
2720                               bool is128Bits, NeonModImmType type, EVT &VT,
2721                               unsigned &Imm, unsigned &OpCmode) {
2722   switch (SplatBitSize) {
2723   default:
2724     llvm_unreachable("unexpected size for isNeonModifiedImm");
2725   case 8: {
2726     if (type != Neon_Mov_Imm)
2727       return false;
2728     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
2729     // Neon movi per byte: Op=0, Cmode=1110.
2730     OpCmode = 0xe;
2731     Imm = SplatBits;
2732     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
2733     break;
2734   }
2735   case 16: {
2736     // Neon move inst per halfword
2737     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
2738     if ((SplatBits & ~0xff) == 0) {
2739       // Value = 0x00nn is 0x00nn LSL 0
2740       // movi: Op=0, Cmode=1000; mvni: Op=1, Cmode=1000
2741       // bic:  Op=1, Cmode=1001;  orr:  Op=0, Cmode=1001
2742       // Op=x, Cmode=100y
2743       Imm = SplatBits;
2744       OpCmode = 0x8;
2745       break;
2746     }
2747     if ((SplatBits & ~0xff00) == 0) {
2748       // Value = 0xnn00 is 0x00nn LSL 8
2749       // movi: Op=0, Cmode=1010; mvni: Op=1, Cmode=1010
2750       // bic:  Op=1, Cmode=1011;  orr:  Op=0, Cmode=1011
2751       // Op=x, Cmode=101x
2752       Imm = SplatBits >> 8;
2753       OpCmode = 0xa;
2754       break;
2755     }
2756     // can't handle any other
2757     return false;
2758   }
2759
2760   case 32: {
2761     // First the LSL variants (MSL is unusable by some interested instructions).
2762
2763     // Neon move instr per word, shift zeros
2764     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
2765     if ((SplatBits & ~0xff) == 0) {
2766       // Value = 0x000000nn is 0x000000nn LSL 0
2767       // movi: Op=0, Cmode= 0000; mvni: Op=1, Cmode= 0000
2768       // bic:  Op=1, Cmode= 0001; orr:  Op=0, Cmode= 0001
2769       // Op=x, Cmode=000x
2770       Imm = SplatBits;
2771       OpCmode = 0;
2772       break;
2773     }
2774     if ((SplatBits & ~0xff00) == 0) {
2775       // Value = 0x0000nn00 is 0x000000nn LSL 8
2776       // movi: Op=0, Cmode= 0010;  mvni: Op=1, Cmode= 0010
2777       // bic:  Op=1, Cmode= 0011;  orr : Op=0, Cmode= 0011
2778       // Op=x, Cmode=001x
2779       Imm = SplatBits >> 8;
2780       OpCmode = 0x2;
2781       break;
2782     }
2783     if ((SplatBits & ~0xff0000) == 0) {
2784       // Value = 0x00nn0000 is 0x000000nn LSL 16
2785       // movi: Op=0, Cmode= 0100; mvni: Op=1, Cmode= 0100
2786       // bic:  Op=1, Cmode= 0101; orr:  Op=0, Cmode= 0101
2787       // Op=x, Cmode=010x
2788       Imm = SplatBits >> 16;
2789       OpCmode = 0x4;
2790       break;
2791     }
2792     if ((SplatBits & ~0xff000000) == 0) {
2793       // Value = 0xnn000000 is 0x000000nn LSL 24
2794       // movi: Op=0, Cmode= 0110; mvni: Op=1, Cmode= 0110
2795       // bic:  Op=1, Cmode= 0111; orr:  Op=0, Cmode= 0111
2796       // Op=x, Cmode=011x
2797       Imm = SplatBits >> 24;
2798       OpCmode = 0x6;
2799       break;
2800     }
2801
2802     // Now the MSL immediates.
2803
2804     // Neon move instr per word, shift ones
2805     if ((SplatBits & ~0xffff) == 0 &&
2806         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
2807       // Value = 0x0000nnff is 0x000000nn MSL 8
2808       // movi: Op=0, Cmode= 1100; mvni: Op=1, Cmode= 1100
2809       // Op=x, Cmode=1100
2810       Imm = SplatBits >> 8;
2811       OpCmode = 0xc;
2812       break;
2813     }
2814     if ((SplatBits & ~0xffffff) == 0 &&
2815         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
2816       // Value = 0x00nnffff is 0x000000nn MSL 16
2817       // movi: Op=1, Cmode= 1101; mvni: Op=1, Cmode= 1101
2818       // Op=x, Cmode=1101
2819       Imm = SplatBits >> 16;
2820       OpCmode = 0xd;
2821       break;
2822     }
2823     // can't handle any other
2824     return false;
2825   }
2826
2827   case 64: {
2828     if (type != Neon_Mov_Imm)
2829       return false;
2830     // Neon move instr bytemask, where each byte is either 0x00 or 0xff.
2831     // movi Op=1, Cmode=1110.
2832     OpCmode = 0x1e;
2833     uint64_t BitMask = 0xff;
2834     uint64_t Val = 0;
2835     unsigned ImmMask = 1;
2836     Imm = 0;
2837     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
2838       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
2839         Val |= BitMask;
2840         Imm |= ImmMask;
2841       } else if ((SplatBits & BitMask) != 0) {
2842         return false;
2843       }
2844       BitMask <<= 8;
2845       ImmMask <<= 1;
2846     }
2847     SplatBits = Val;
2848     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
2849     break;
2850   }
2851   }
2852
2853   return true;
2854 }
2855
2856 static SDValue PerformANDCombine(SDNode *N,
2857                                  TargetLowering::DAGCombinerInfo &DCI) {
2858
2859   SelectionDAG &DAG = DCI.DAG;
2860   SDLoc DL(N);
2861   EVT VT = N->getValueType(0);
2862
2863   // We're looking for an SRA/SHL pair which form an SBFX.
2864
2865   if (VT != MVT::i32 && VT != MVT::i64)
2866     return SDValue();
2867
2868   if (!isa<ConstantSDNode>(N->getOperand(1)))
2869     return SDValue();
2870
2871   uint64_t TruncMask = N->getConstantOperandVal(1);
2872   if (!isMask_64(TruncMask))
2873     return SDValue();
2874
2875   uint64_t Width = CountPopulation_64(TruncMask);
2876   SDValue Shift = N->getOperand(0);
2877
2878   if (Shift.getOpcode() != ISD::SRL)
2879     return SDValue();
2880
2881   if (!isa<ConstantSDNode>(Shift->getOperand(1)))
2882     return SDValue();
2883   uint64_t LSB = Shift->getConstantOperandVal(1);
2884
2885   if (LSB > VT.getSizeInBits() || Width > VT.getSizeInBits())
2886     return SDValue();
2887
2888   return DAG.getNode(AArch64ISD::UBFX, DL, VT, Shift.getOperand(0),
2889                      DAG.getConstant(LSB, MVT::i64),
2890                      DAG.getConstant(LSB + Width - 1, MVT::i64));
2891 }
2892
2893 /// For a true bitfield insert, the bits getting into that contiguous mask
2894 /// should come from the low part of an existing value: they must be formed from
2895 /// a compatible SHL operation (unless they're already low). This function
2896 /// checks that condition and returns the least-significant bit that's
2897 /// intended. If the operation not a field preparation, -1 is returned.
2898 static int32_t getLSBForBFI(SelectionDAG &DAG, SDLoc DL, EVT VT,
2899                             SDValue &MaskedVal, uint64_t Mask) {
2900   if (!isShiftedMask_64(Mask))
2901     return -1;
2902
2903   // Now we need to alter MaskedVal so that it is an appropriate input for a BFI
2904   // instruction. BFI will do a left-shift by LSB before applying the mask we've
2905   // spotted, so in general we should pre-emptively "undo" that by making sure
2906   // the incoming bits have had a right-shift applied to them.
2907   //
2908   // This right shift, however, will combine with existing left/right shifts. In
2909   // the simplest case of a completely straight bitfield operation, it will be
2910   // expected to completely cancel out with an existing SHL. More complicated
2911   // cases (e.g. bitfield to bitfield copy) may still need a real shift before
2912   // the BFI.
2913
2914   uint64_t LSB = countTrailingZeros(Mask);
2915   int64_t ShiftRightRequired = LSB;
2916   if (MaskedVal.getOpcode() == ISD::SHL &&
2917       isa<ConstantSDNode>(MaskedVal.getOperand(1))) {
2918     ShiftRightRequired -= MaskedVal.getConstantOperandVal(1);
2919     MaskedVal = MaskedVal.getOperand(0);
2920   } else if (MaskedVal.getOpcode() == ISD::SRL &&
2921              isa<ConstantSDNode>(MaskedVal.getOperand(1))) {
2922     ShiftRightRequired += MaskedVal.getConstantOperandVal(1);
2923     MaskedVal = MaskedVal.getOperand(0);
2924   }
2925
2926   if (ShiftRightRequired > 0)
2927     MaskedVal = DAG.getNode(ISD::SRL, DL, VT, MaskedVal,
2928                             DAG.getConstant(ShiftRightRequired, MVT::i64));
2929   else if (ShiftRightRequired < 0) {
2930     // We could actually end up with a residual left shift, for example with
2931     // "struc.bitfield = val << 1".
2932     MaskedVal = DAG.getNode(ISD::SHL, DL, VT, MaskedVal,
2933                             DAG.getConstant(-ShiftRightRequired, MVT::i64));
2934   }
2935
2936   return LSB;
2937 }
2938
2939 /// Searches from N for an existing AArch64ISD::BFI node, possibly surrounded by
2940 /// a mask and an extension. Returns true if a BFI was found and provides
2941 /// information on its surroundings.
2942 static bool findMaskedBFI(SDValue N, SDValue &BFI, uint64_t &Mask,
2943                           bool &Extended) {
2944   Extended = false;
2945   if (N.getOpcode() == ISD::ZERO_EXTEND) {
2946     Extended = true;
2947     N = N.getOperand(0);
2948   }
2949
2950   if (N.getOpcode() == ISD::AND && isa<ConstantSDNode>(N.getOperand(1))) {
2951     Mask = N->getConstantOperandVal(1);
2952     N = N.getOperand(0);
2953   } else {
2954     // Mask is the whole width.
2955     Mask = -1ULL >> (64 - N.getValueType().getSizeInBits());
2956   }
2957
2958   if (N.getOpcode() == AArch64ISD::BFI) {
2959     BFI = N;
2960     return true;
2961   }
2962
2963   return false;
2964 }
2965
2966 /// Try to combine a subtree (rooted at an OR) into a "masked BFI" node, which
2967 /// is roughly equivalent to (and (BFI ...), mask). This form is used because it
2968 /// can often be further combined with a larger mask. Ultimately, we want mask
2969 /// to be 2^32-1 or 2^64-1 so the AND can be skipped.
2970 static SDValue tryCombineToBFI(SDNode *N,
2971                                TargetLowering::DAGCombinerInfo &DCI,
2972                                const AArch64Subtarget *Subtarget) {
2973   SelectionDAG &DAG = DCI.DAG;
2974   SDLoc DL(N);
2975   EVT VT = N->getValueType(0);
2976
2977   assert(N->getOpcode() == ISD::OR && "Unexpected root");
2978
2979   // We need the LHS to be (and SOMETHING, MASK). Find out what that mask is or
2980   // abandon the effort.
2981   SDValue LHS = N->getOperand(0);
2982   if (LHS.getOpcode() != ISD::AND)
2983     return SDValue();
2984
2985   uint64_t LHSMask;
2986   if (isa<ConstantSDNode>(LHS.getOperand(1)))
2987     LHSMask = LHS->getConstantOperandVal(1);
2988   else
2989     return SDValue();
2990
2991   // We also need the RHS to be (and SOMETHING, MASK). Find out what that mask
2992   // is or abandon the effort.
2993   SDValue RHS = N->getOperand(1);
2994   if (RHS.getOpcode() != ISD::AND)
2995     return SDValue();
2996
2997   uint64_t RHSMask;
2998   if (isa<ConstantSDNode>(RHS.getOperand(1)))
2999     RHSMask = RHS->getConstantOperandVal(1);
3000   else
3001     return SDValue();
3002
3003   // Can't do anything if the masks are incompatible.
3004   if (LHSMask & RHSMask)
3005     return SDValue();
3006
3007   // Now we need one of the masks to be a contiguous field. Without loss of
3008   // generality that should be the RHS one.
3009   SDValue Bitfield = LHS.getOperand(0);
3010   if (getLSBForBFI(DAG, DL, VT, Bitfield, LHSMask) != -1) {
3011     // We know that LHS is a candidate new value, and RHS isn't already a better
3012     // one.
3013     std::swap(LHS, RHS);
3014     std::swap(LHSMask, RHSMask);
3015   }
3016
3017   // We've done our best to put the right operands in the right places, all we
3018   // can do now is check whether a BFI exists.
3019   Bitfield = RHS.getOperand(0);
3020   int32_t LSB = getLSBForBFI(DAG, DL, VT, Bitfield, RHSMask);
3021   if (LSB == -1)
3022     return SDValue();
3023
3024   uint32_t Width = CountPopulation_64(RHSMask);
3025   assert(Width && "Expected non-zero bitfield width");
3026
3027   SDValue BFI = DAG.getNode(AArch64ISD::BFI, DL, VT,
3028                             LHS.getOperand(0), Bitfield,
3029                             DAG.getConstant(LSB, MVT::i64),
3030                             DAG.getConstant(Width, MVT::i64));
3031
3032   // Mask is trivial
3033   if ((LHSMask | RHSMask) == (-1ULL >> (64 - VT.getSizeInBits())))
3034     return BFI;
3035
3036   return DAG.getNode(ISD::AND, DL, VT, BFI,
3037                      DAG.getConstant(LHSMask | RHSMask, VT));
3038 }
3039
3040 /// Search for the bitwise combining (with careful masks) of a MaskedBFI and its
3041 /// original input. This is surprisingly common because SROA splits things up
3042 /// into i8 chunks, so the originally detected MaskedBFI may actually only act
3043 /// on the low (say) byte of a word. This is then orred into the rest of the
3044 /// word afterwards.
3045 ///
3046 /// Basic input: (or (and OLDFIELD, MASK1), (MaskedBFI MASK2, OLDFIELD, ...)).
3047 ///
3048 /// If MASK1 and MASK2 are compatible, we can fold the whole thing into the
3049 /// MaskedBFI. We can also deal with a certain amount of extend/truncate being
3050 /// involved.
3051 static SDValue tryCombineToLargerBFI(SDNode *N,
3052                                      TargetLowering::DAGCombinerInfo &DCI,
3053                                      const AArch64Subtarget *Subtarget) {
3054   SelectionDAG &DAG = DCI.DAG;
3055   SDLoc DL(N);
3056   EVT VT = N->getValueType(0);
3057
3058   // First job is to hunt for a MaskedBFI on either the left or right. Swap
3059   // operands if it's actually on the right.
3060   SDValue BFI;
3061   SDValue PossExtraMask;
3062   uint64_t ExistingMask = 0;
3063   bool Extended = false;
3064   if (findMaskedBFI(N->getOperand(0), BFI, ExistingMask, Extended))
3065     PossExtraMask = N->getOperand(1);
3066   else if (findMaskedBFI(N->getOperand(1), BFI, ExistingMask, Extended))
3067     PossExtraMask = N->getOperand(0);
3068   else
3069     return SDValue();
3070
3071   // We can only combine a BFI with another compatible mask.
3072   if (PossExtraMask.getOpcode() != ISD::AND ||
3073       !isa<ConstantSDNode>(PossExtraMask.getOperand(1)))
3074     return SDValue();
3075
3076   uint64_t ExtraMask = PossExtraMask->getConstantOperandVal(1);
3077
3078   // Masks must be compatible.
3079   if (ExtraMask & ExistingMask)
3080     return SDValue();
3081
3082   SDValue OldBFIVal = BFI.getOperand(0);
3083   SDValue NewBFIVal = BFI.getOperand(1);
3084   if (Extended) {
3085     // We skipped a ZERO_EXTEND above, so the input to the MaskedBFIs should be
3086     // 32-bit and we'll be forming a 64-bit MaskedBFI. The MaskedBFI arguments
3087     // need to be made compatible.
3088     assert(VT == MVT::i64 && BFI.getValueType() == MVT::i32
3089            && "Invalid types for BFI");
3090     OldBFIVal = DAG.getNode(ISD::ANY_EXTEND, DL, VT, OldBFIVal);
3091     NewBFIVal = DAG.getNode(ISD::ANY_EXTEND, DL, VT, NewBFIVal);
3092   }
3093
3094   // We need the MaskedBFI to be combined with a mask of the *same* value.
3095   if (PossExtraMask.getOperand(0) != OldBFIVal)
3096     return SDValue();
3097
3098   BFI = DAG.getNode(AArch64ISD::BFI, DL, VT,
3099                     OldBFIVal, NewBFIVal,
3100                     BFI.getOperand(2), BFI.getOperand(3));
3101
3102   // If the masking is trivial, we don't need to create it.
3103   if ((ExtraMask | ExistingMask) == (-1ULL >> (64 - VT.getSizeInBits())))
3104     return BFI;
3105
3106   return DAG.getNode(ISD::AND, DL, VT, BFI,
3107                      DAG.getConstant(ExtraMask | ExistingMask, VT));
3108 }
3109
3110 /// An EXTR instruction is made up of two shifts, ORed together. This helper
3111 /// searches for and classifies those shifts.
3112 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
3113                          bool &FromHi) {
3114   if (N.getOpcode() == ISD::SHL)
3115     FromHi = false;
3116   else if (N.getOpcode() == ISD::SRL)
3117     FromHi = true;
3118   else
3119     return false;
3120
3121   if (!isa<ConstantSDNode>(N.getOperand(1)))
3122     return false;
3123
3124   ShiftAmount = N->getConstantOperandVal(1);
3125   Src = N->getOperand(0);
3126   return true;
3127 }
3128
3129 /// EXTR instruction extracts a contiguous chunk of bits from two existing
3130 /// registers viewed as a high/low pair. This function looks for the pattern:
3131 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
3132 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
3133 /// independent.
3134 static SDValue tryCombineToEXTR(SDNode *N,
3135                                 TargetLowering::DAGCombinerInfo &DCI) {
3136   SelectionDAG &DAG = DCI.DAG;
3137   SDLoc DL(N);
3138   EVT VT = N->getValueType(0);
3139
3140   assert(N->getOpcode() == ISD::OR && "Unexpected root");
3141
3142   if (VT != MVT::i32 && VT != MVT::i64)
3143     return SDValue();
3144
3145   SDValue LHS;
3146   uint32_t ShiftLHS = 0;
3147   bool LHSFromHi = 0;
3148   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
3149     return SDValue();
3150
3151   SDValue RHS;
3152   uint32_t ShiftRHS = 0;
3153   bool RHSFromHi = 0;
3154   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
3155     return SDValue();
3156
3157   // If they're both trying to come from the high part of the register, they're
3158   // not really an EXTR.
3159   if (LHSFromHi == RHSFromHi)
3160     return SDValue();
3161
3162   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
3163     return SDValue();
3164
3165   if (LHSFromHi) {
3166     std::swap(LHS, RHS);
3167     std::swap(ShiftLHS, ShiftRHS);
3168   }
3169
3170   return DAG.getNode(AArch64ISD::EXTR, DL, VT,
3171                      LHS, RHS,
3172                      DAG.getConstant(ShiftRHS, MVT::i64));
3173 }
3174
3175 /// Target-specific dag combine xforms for ISD::OR
3176 static SDValue PerformORCombine(SDNode *N,
3177                                 TargetLowering::DAGCombinerInfo &DCI,
3178                                 const AArch64Subtarget *Subtarget) {
3179
3180   SelectionDAG &DAG = DCI.DAG;
3181   SDLoc DL(N);
3182   EVT VT = N->getValueType(0);
3183
3184   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
3185     return SDValue();
3186
3187   // Attempt to recognise bitfield-insert operations.
3188   SDValue Res = tryCombineToBFI(N, DCI, Subtarget);
3189   if (Res.getNode())
3190     return Res;
3191
3192   // Attempt to combine an existing MaskedBFI operation into one with a larger
3193   // mask.
3194   Res = tryCombineToLargerBFI(N, DCI, Subtarget);
3195   if (Res.getNode())
3196     return Res;
3197
3198   Res = tryCombineToEXTR(N, DCI);
3199   if (Res.getNode())
3200     return Res;
3201
3202   if (!Subtarget->hasNEON())
3203     return SDValue();
3204
3205   // Attempt to use vector immediate-form BSL
3206   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
3207
3208   SDValue N0 = N->getOperand(0);
3209   if (N0.getOpcode() != ISD::AND)
3210     return SDValue();
3211
3212   SDValue N1 = N->getOperand(1);
3213   if (N1.getOpcode() != ISD::AND)
3214     return SDValue();
3215
3216   if (VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
3217     APInt SplatUndef;
3218     unsigned SplatBitSize;
3219     bool HasAnyUndefs;
3220     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
3221     APInt SplatBits0;
3222     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
3223                                       HasAnyUndefs) &&
3224         !HasAnyUndefs) {
3225       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
3226       APInt SplatBits1;
3227       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
3228                                         HasAnyUndefs) &&
3229           !HasAnyUndefs && SplatBits0 == ~SplatBits1) {
3230         // Canonicalize the vector type to make instruction selection simpler.
3231         EVT CanonicalVT = VT.is128BitVector() ? MVT::v16i8 : MVT::v8i8;
3232         SDValue Result = DAG.getNode(AArch64ISD::NEON_BSL, DL, CanonicalVT,
3233                                      N0->getOperand(1), N0->getOperand(0),
3234                                      N1->getOperand(0));
3235         return DAG.getNode(ISD::BITCAST, DL, VT, Result);
3236       }
3237     }
3238   }
3239
3240   return SDValue();
3241 }
3242
3243 /// Target-specific dag combine xforms for ISD::SRA
3244 static SDValue PerformSRACombine(SDNode *N,
3245                                  TargetLowering::DAGCombinerInfo &DCI) {
3246
3247   SelectionDAG &DAG = DCI.DAG;
3248   SDLoc DL(N);
3249   EVT VT = N->getValueType(0);
3250
3251   // We're looking for an SRA/SHL pair which form an SBFX.
3252
3253   if (VT != MVT::i32 && VT != MVT::i64)
3254     return SDValue();
3255
3256   if (!isa<ConstantSDNode>(N->getOperand(1)))
3257     return SDValue();
3258
3259   uint64_t ExtraSignBits = N->getConstantOperandVal(1);
3260   SDValue Shift = N->getOperand(0);
3261
3262   if (Shift.getOpcode() != ISD::SHL)
3263     return SDValue();
3264
3265   if (!isa<ConstantSDNode>(Shift->getOperand(1)))
3266     return SDValue();
3267
3268   uint64_t BitsOnLeft = Shift->getConstantOperandVal(1);
3269   uint64_t Width = VT.getSizeInBits() - ExtraSignBits;
3270   uint64_t LSB = VT.getSizeInBits() - Width - BitsOnLeft;
3271
3272   if (LSB > VT.getSizeInBits() || Width > VT.getSizeInBits())
3273     return SDValue();
3274
3275   return DAG.getNode(AArch64ISD::SBFX, DL, VT, Shift.getOperand(0),
3276                      DAG.getConstant(LSB, MVT::i64),
3277                      DAG.getConstant(LSB + Width - 1, MVT::i64));
3278 }
3279
3280 /// Check if this is a valid build_vector for the immediate operand of
3281 /// a vector shift operation, where all the elements of the build_vector
3282 /// must have the same constant integer value.
3283 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
3284   // Ignore bit_converts.
3285   while (Op.getOpcode() == ISD::BITCAST)
3286     Op = Op.getOperand(0);
3287   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
3288   APInt SplatBits, SplatUndef;
3289   unsigned SplatBitSize;
3290   bool HasAnyUndefs;
3291   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
3292                                       HasAnyUndefs, ElementBits) ||
3293       SplatBitSize > ElementBits)
3294     return false;
3295   Cnt = SplatBits.getSExtValue();
3296   return true;
3297 }
3298
3299 /// Check if this is a valid build_vector for the immediate operand of
3300 /// a vector shift left operation.  That value must be in the range:
3301 /// 0 <= Value < ElementBits
3302 static bool isVShiftLImm(SDValue Op, EVT VT, int64_t &Cnt) {
3303   assert(VT.isVector() && "vector shift count is not a vector type");
3304   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3305   if (!getVShiftImm(Op, ElementBits, Cnt))
3306     return false;
3307   return (Cnt >= 0 && Cnt < ElementBits);
3308 }
3309
3310 /// Check if this is a valid build_vector for the immediate operand of a
3311 /// vector shift right operation. The value must be in the range:
3312 ///   1 <= Value <= ElementBits
3313 static bool isVShiftRImm(SDValue Op, EVT VT, int64_t &Cnt) {
3314   assert(VT.isVector() && "vector shift count is not a vector type");
3315   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
3316   if (!getVShiftImm(Op, ElementBits, Cnt))
3317     return false;
3318   return (Cnt >= 1 && Cnt <= ElementBits);
3319 }
3320
3321 /// Checks for immediate versions of vector shifts and lowers them.
3322 static SDValue PerformShiftCombine(SDNode *N,
3323                                    TargetLowering::DAGCombinerInfo &DCI,
3324                                    const AArch64Subtarget *ST) {
3325   SelectionDAG &DAG = DCI.DAG;
3326   EVT VT = N->getValueType(0);
3327   if (N->getOpcode() == ISD::SRA && (VT == MVT::i32 || VT == MVT::i64))
3328     return PerformSRACombine(N, DCI);
3329
3330   // Nothing to be done for scalar shifts.
3331   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3332   if (!VT.isVector() || !TLI.isTypeLegal(VT))
3333     return SDValue();
3334
3335   assert(ST->hasNEON() && "unexpected vector shift");
3336   int64_t Cnt;
3337
3338   switch (N->getOpcode()) {
3339   default:
3340     llvm_unreachable("unexpected shift opcode");
3341
3342   case ISD::SHL:
3343     if (isVShiftLImm(N->getOperand(1), VT, Cnt)) {
3344       SDValue RHS =
3345           DAG.getNode(AArch64ISD::NEON_DUPIMM, SDLoc(N->getOperand(1)), VT,
3346                       DAG.getConstant(Cnt, MVT::i32));
3347       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0), RHS);
3348     }
3349     break;
3350
3351   case ISD::SRA:
3352   case ISD::SRL:
3353     if (isVShiftRImm(N->getOperand(1), VT, Cnt)) {
3354       SDValue RHS =
3355           DAG.getNode(AArch64ISD::NEON_DUPIMM, SDLoc(N->getOperand(1)), VT,
3356                       DAG.getConstant(Cnt, MVT::i32));
3357       return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N->getOperand(0), RHS);
3358     }
3359     break;
3360   }
3361
3362   return SDValue();
3363 }
3364
3365 /// ARM-specific DAG combining for intrinsics.
3366 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
3367   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3368
3369   switch (IntNo) {
3370   default:
3371     // Don't do anything for most intrinsics.
3372     break;
3373
3374   case Intrinsic::arm_neon_vqshifts:
3375   case Intrinsic::arm_neon_vqshiftu:
3376     EVT VT = N->getOperand(1).getValueType();
3377     int64_t Cnt;
3378     if (!isVShiftLImm(N->getOperand(2), VT, Cnt))
3379       break;
3380     unsigned VShiftOpc = (IntNo == Intrinsic::arm_neon_vqshifts)
3381                              ? AArch64ISD::NEON_QSHLs
3382                              : AArch64ISD::NEON_QSHLu;
3383     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
3384                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
3385   }
3386
3387   return SDValue();
3388 }
3389
3390 SDValue
3391 AArch64TargetLowering::PerformDAGCombine(SDNode *N,
3392                                          DAGCombinerInfo &DCI) const {
3393   switch (N->getOpcode()) {
3394   default: break;
3395   case ISD::AND: return PerformANDCombine(N, DCI);
3396   case ISD::OR: return PerformORCombine(N, DCI, getSubtarget());
3397   case ISD::SHL:
3398   case ISD::SRA:
3399   case ISD::SRL:
3400     return PerformShiftCombine(N, DCI, getSubtarget());
3401   case ISD::INTRINSIC_WO_CHAIN:
3402     return PerformIntrinsicCombine(N, DCI.DAG);
3403   }
3404   return SDValue();
3405 }
3406
3407 bool
3408 AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3409   VT = VT.getScalarType();
3410
3411   if (!VT.isSimple())
3412     return false;
3413
3414   switch (VT.getSimpleVT().SimpleTy) {
3415   case MVT::f16:
3416   case MVT::f32:
3417   case MVT::f64:
3418     return true;
3419   case MVT::f128:
3420     return false;
3421   default:
3422     break;
3423   }
3424
3425   return false;
3426 }
3427
3428 // If this is a case we can't handle, return null and let the default
3429 // expansion code take care of it.
3430 SDValue
3431 AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
3432                                          const AArch64Subtarget *ST) const {
3433
3434   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
3435   SDLoc DL(Op);
3436   EVT VT = Op.getValueType();
3437
3438   APInt SplatBits, SplatUndef;
3439   unsigned SplatBitSize;
3440   bool HasAnyUndefs;
3441
3442   // Note we favor lowering MOVI over MVNI.
3443   // This has implications on the definition of patterns in TableGen to select
3444   // BIC immediate instructions but not ORR immediate instructions.
3445   // If this lowering order is changed, TableGen patterns for BIC immediate and
3446   // ORR immediate instructions have to be updated.
3447   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
3448     if (SplatBitSize <= 64) {
3449       // First attempt to use vector immediate-form MOVI
3450       EVT NeonMovVT;
3451       unsigned Imm = 0;
3452       unsigned OpCmode = 0;
3453
3454       if (isNeonModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
3455                             SplatBitSize, DAG, VT.is128BitVector(),
3456                             Neon_Mov_Imm, NeonMovVT, Imm, OpCmode)) {
3457         SDValue ImmVal = DAG.getTargetConstant(Imm, MVT::i32);
3458         SDValue OpCmodeVal = DAG.getConstant(OpCmode, MVT::i32);
3459
3460         if (ImmVal.getNode() && OpCmodeVal.getNode()) {
3461           SDValue NeonMov = DAG.getNode(AArch64ISD::NEON_MOVIMM, DL, NeonMovVT,
3462                                         ImmVal, OpCmodeVal);
3463           return DAG.getNode(ISD::BITCAST, DL, VT, NeonMov);
3464         }
3465       }
3466
3467       // Then attempt to use vector immediate-form MVNI
3468       uint64_t NegatedImm = (~SplatBits).getZExtValue();
3469       if (isNeonModifiedImm(NegatedImm, SplatUndef.getZExtValue(), SplatBitSize,
3470                             DAG, VT.is128BitVector(), Neon_Mvn_Imm, NeonMovVT,
3471                             Imm, OpCmode)) {
3472         SDValue ImmVal = DAG.getTargetConstant(Imm, MVT::i32);
3473         SDValue OpCmodeVal = DAG.getConstant(OpCmode, MVT::i32);
3474         if (ImmVal.getNode() && OpCmodeVal.getNode()) {
3475           SDValue NeonMov = DAG.getNode(AArch64ISD::NEON_MVNIMM, DL, NeonMovVT,
3476                                         ImmVal, OpCmodeVal);
3477           return DAG.getNode(ISD::BITCAST, DL, VT, NeonMov);
3478         }
3479       }
3480
3481       // Attempt to use vector immediate-form FMOV
3482       if (((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) ||
3483           (VT == MVT::v2f64 && SplatBitSize == 64)) {
3484         APFloat RealVal(
3485             SplatBitSize == 32 ? APFloat::IEEEsingle : APFloat::IEEEdouble,
3486             SplatBits);
3487         uint32_t ImmVal;
3488         if (A64Imms::isFPImm(RealVal, ImmVal)) {
3489           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
3490           return DAG.getNode(AArch64ISD::NEON_FMOVIMM, DL, VT, Val);
3491         }
3492       }
3493     }
3494   }
3495   return SDValue();
3496 }
3497
3498 SDValue
3499 AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
3500                                                 SelectionDAG &DAG) const {
3501   SDValue V1 = Op.getOperand(0);
3502   SDLoc dl(Op);
3503   EVT VT = Op.getValueType();
3504   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
3505
3506   // Convert shuffles that are directly supported on NEON to target-specific
3507   // DAG nodes, instead of keeping them as shuffles and matching them again
3508   // during code selection.  This is more efficient and avoids the possibility
3509   // of inconsistencies between legalization and selection.
3510   ArrayRef<int> ShuffleMask = SVN->getMask();
3511
3512   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3513   if (EltSize <= 64) {
3514     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
3515       int Lane = SVN->getSplatIndex();
3516       // If this is undef splat, generate it via "just" vdup, if possible.
3517       if (Lane == -1) Lane = 0;
3518
3519       return DAG.getNode(AArch64ISD::NEON_VDUPLANE, dl, VT, V1,
3520                          DAG.getConstant(Lane, MVT::i64));
3521     }
3522   }
3523
3524   return SDValue();
3525 }
3526
3527 AArch64TargetLowering::ConstraintType
3528 AArch64TargetLowering::getConstraintType(const std::string &Constraint) const {
3529   if (Constraint.size() == 1) {
3530     switch (Constraint[0]) {
3531     default: break;
3532     case 'w': // An FP/SIMD vector register
3533       return C_RegisterClass;
3534     case 'I': // Constant that can be used with an ADD instruction
3535     case 'J': // Constant that can be used with a SUB instruction
3536     case 'K': // Constant that can be used with a 32-bit logical instruction
3537     case 'L': // Constant that can be used with a 64-bit logical instruction
3538     case 'M': // Constant that can be used as a 32-bit MOV immediate
3539     case 'N': // Constant that can be used as a 64-bit MOV immediate
3540     case 'Y': // Floating point constant zero
3541     case 'Z': // Integer constant zero
3542       return C_Other;
3543     case 'Q': // A memory reference with base register and no offset
3544       return C_Memory;
3545     case 'S': // A symbolic address
3546       return C_Other;
3547     }
3548   }
3549
3550   // FIXME: Ump, Utf, Usa, Ush
3551   // Ump: A memory address suitable for ldp/stp in SI, DI, SF and DF modes,
3552   //      whatever they may be
3553   // Utf: A memory address suitable for ldp/stp in TF mode, whatever it may be
3554   // Usa: An absolute symbolic address
3555   // Ush: The high part (bits 32:12) of a pc-relative symbolic address
3556   assert(Constraint != "Ump" && Constraint != "Utf" && Constraint != "Usa"
3557          && Constraint != "Ush" && "Unimplemented constraints");
3558
3559   return TargetLowering::getConstraintType(Constraint);
3560 }
3561
3562 TargetLowering::ConstraintWeight
3563 AArch64TargetLowering::getSingleConstraintMatchWeight(AsmOperandInfo &Info,
3564                                                 const char *Constraint) const {
3565
3566   llvm_unreachable("Constraint weight unimplemented");
3567 }
3568
3569 void
3570 AArch64TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3571                                                     std::string &Constraint,
3572                                                     std::vector<SDValue> &Ops,
3573                                                     SelectionDAG &DAG) const {
3574   SDValue Result(0, 0);
3575
3576   // Only length 1 constraints are C_Other.
3577   if (Constraint.size() != 1) return;
3578
3579   // Only C_Other constraints get lowered like this. That means constants for us
3580   // so return early if there's no hope the constraint can be lowered.
3581
3582   switch(Constraint[0]) {
3583   default: break;
3584   case 'I': case 'J': case 'K': case 'L':
3585   case 'M': case 'N': case 'Z': {
3586     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3587     if (!C)
3588       return;
3589
3590     uint64_t CVal = C->getZExtValue();
3591     uint32_t Bits;
3592
3593     switch (Constraint[0]) {
3594     default:
3595       // FIXME: 'M' and 'N' are MOV pseudo-insts -- unsupported in assembly. 'J'
3596       // is a peculiarly useless SUB constraint.
3597       llvm_unreachable("Unimplemented C_Other constraint");
3598     case 'I':
3599       if (CVal <= 0xfff)
3600         break;
3601       return;
3602     case 'K':
3603       if (A64Imms::isLogicalImm(32, CVal, Bits))
3604         break;
3605       return;
3606     case 'L':
3607       if (A64Imms::isLogicalImm(64, CVal, Bits))
3608         break;
3609       return;
3610     case 'Z':
3611       if (CVal == 0)
3612         break;
3613       return;
3614     }
3615
3616     Result = DAG.getTargetConstant(CVal, Op.getValueType());
3617     break;
3618   }
3619   case 'S': {
3620     // An absolute symbolic address or label reference.
3621     if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
3622       Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
3623                                           GA->getValueType(0));
3624     } else if (const BlockAddressSDNode *BA
3625                  = dyn_cast<BlockAddressSDNode>(Op)) {
3626       Result = DAG.getTargetBlockAddress(BA->getBlockAddress(),
3627                                          BA->getValueType(0));
3628     } else if (const ExternalSymbolSDNode *ES
3629                  = dyn_cast<ExternalSymbolSDNode>(Op)) {
3630       Result = DAG.getTargetExternalSymbol(ES->getSymbol(),
3631                                            ES->getValueType(0));
3632     } else
3633       return;
3634     break;
3635   }
3636   case 'Y':
3637     if (const ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
3638       if (CFP->isExactlyValue(0.0)) {
3639         Result = DAG.getTargetConstantFP(0.0, CFP->getValueType(0));
3640         break;
3641       }
3642     }
3643     return;
3644   }
3645
3646   if (Result.getNode()) {
3647     Ops.push_back(Result);
3648     return;
3649   }
3650
3651   // It's an unknown constraint for us. Let generic code have a go.
3652   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3653 }
3654
3655 std::pair<unsigned, const TargetRegisterClass*>
3656 AArch64TargetLowering::getRegForInlineAsmConstraint(
3657                                                   const std::string &Constraint,
3658                                                   MVT VT) const {
3659   if (Constraint.size() == 1) {
3660     switch (Constraint[0]) {
3661     case 'r':
3662       if (VT.getSizeInBits() <= 32)
3663         return std::make_pair(0U, &AArch64::GPR32RegClass);
3664       else if (VT == MVT::i64)
3665         return std::make_pair(0U, &AArch64::GPR64RegClass);
3666       break;
3667     case 'w':
3668       if (VT == MVT::f16)
3669         return std::make_pair(0U, &AArch64::FPR16RegClass);
3670       else if (VT == MVT::f32)
3671         return std::make_pair(0U, &AArch64::FPR32RegClass);
3672       else if (VT.getSizeInBits() == 64)
3673         return std::make_pair(0U, &AArch64::FPR64RegClass);
3674       else if (VT.getSizeInBits() == 128)
3675         return std::make_pair(0U, &AArch64::FPR128RegClass);
3676       break;
3677     }
3678   }
3679
3680   // Use the default implementation in TargetLowering to convert the register
3681   // constraint into a member of a register class.
3682   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3683 }