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