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