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