]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
Merge ^/head r319480 through r319547.
[FreeBSD/FreeBSD.git] / contrib / llvm / 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 implements the AArch64TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "AArch64CallingConvention.h"
15 #include "AArch64MachineFunctionInfo.h"
16 #include "AArch64ISelLowering.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64RegisterInfo.h"
19 #include "AArch64Subtarget.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "Utils/AArch64BaseInfo.h"
22 #include "llvm/ADT/APFloat.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Analysis/VectorUtils.h"
33 #include "llvm/CodeGen/CallingConvLower.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineInstr.h"
38 #include "llvm/CodeGen/MachineInstrBuilder.h"
39 #include "llvm/CodeGen/MachineMemOperand.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/MachineValueType.h"
42 #include "llvm/CodeGen/RuntimeLibcalls.h"
43 #include "llvm/CodeGen/SelectionDAG.h"
44 #include "llvm/CodeGen/SelectionDAGNodes.h"
45 #include "llvm/CodeGen/ValueTypes.h"
46 #include "llvm/IR/Attributes.h"
47 #include "llvm/IR/Constants.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/DebugLoc.h"
50 #include "llvm/IR/DerivedTypes.h"
51 #include "llvm/IR/Function.h"
52 #include "llvm/IR/GetElementPtrTypeIterator.h"
53 #include "llvm/IR/GlobalValue.h"
54 #include "llvm/IR/Instruction.h"
55 #include "llvm/IR/Instructions.h"
56 #include "llvm/IR/Intrinsics.h"
57 #include "llvm/IR/IRBuilder.h"
58 #include "llvm/IR/Module.h"
59 #include "llvm/IR/OperandTraits.h"
60 #include "llvm/IR/Type.h"
61 #include "llvm/IR/Use.h"
62 #include "llvm/IR/Value.h"
63 #include "llvm/MC/MCRegisterInfo.h"
64 #include "llvm/Support/Casting.h"
65 #include "llvm/Support/CodeGen.h"
66 #include "llvm/Support/CommandLine.h"
67 #include "llvm/Support/Compiler.h"
68 #include "llvm/Support/Debug.h"
69 #include "llvm/Support/ErrorHandling.h"
70 #include "llvm/Support/KnownBits.h"
71 #include "llvm/Support/MathExtras.h"
72 #include "llvm/Support/raw_ostream.h"
73 #include "llvm/Target/TargetCallingConv.h"
74 #include "llvm/Target/TargetInstrInfo.h"
75 #include "llvm/Target/TargetMachine.h"
76 #include "llvm/Target/TargetOptions.h"
77 #include <algorithm>
78 #include <bitset>
79 #include <cassert>
80 #include <cctype>
81 #include <cstdint>
82 #include <cstdlib>
83 #include <iterator>
84 #include <limits>
85 #include <tuple>
86 #include <utility>
87 #include <vector>
88
89 using namespace llvm;
90
91 #define DEBUG_TYPE "aarch64-lower"
92
93 STATISTIC(NumTailCalls, "Number of tail calls");
94 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
95 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
96
97 static cl::opt<bool>
98 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
99                            cl::desc("Allow AArch64 SLI/SRI formation"),
100                            cl::init(false));
101
102 // FIXME: The necessary dtprel relocations don't seem to be supported
103 // well in the GNU bfd and gold linkers at the moment. Therefore, by
104 // default, for now, fall back to GeneralDynamic code generation.
105 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
106     "aarch64-elf-ldtls-generation", cl::Hidden,
107     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
108     cl::init(false));
109
110 static cl::opt<bool>
111 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
112                          cl::desc("Enable AArch64 logical imm instruction "
113                                   "optimization"),
114                          cl::init(true));
115
116 /// Value type used for condition codes.
117 static const MVT MVT_CC = MVT::i32;
118
119 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
120                                              const AArch64Subtarget &STI)
121     : TargetLowering(TM), Subtarget(&STI) {
122   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
123   // we have to make something up. Arbitrarily, choose ZeroOrOne.
124   setBooleanContents(ZeroOrOneBooleanContent);
125   // When comparing vectors the result sets the different elements in the
126   // vector to all-one or all-zero.
127   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
128
129   // Set up the register classes.
130   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
131   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
132
133   if (Subtarget->hasFPARMv8()) {
134     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
135     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
136     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
137     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
138   }
139
140   if (Subtarget->hasNEON()) {
141     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
142     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
143     // Someone set us up the NEON.
144     addDRTypeForNEON(MVT::v2f32);
145     addDRTypeForNEON(MVT::v8i8);
146     addDRTypeForNEON(MVT::v4i16);
147     addDRTypeForNEON(MVT::v2i32);
148     addDRTypeForNEON(MVT::v1i64);
149     addDRTypeForNEON(MVT::v1f64);
150     addDRTypeForNEON(MVT::v4f16);
151
152     addQRTypeForNEON(MVT::v4f32);
153     addQRTypeForNEON(MVT::v2f64);
154     addQRTypeForNEON(MVT::v16i8);
155     addQRTypeForNEON(MVT::v8i16);
156     addQRTypeForNEON(MVT::v4i32);
157     addQRTypeForNEON(MVT::v2i64);
158     addQRTypeForNEON(MVT::v8f16);
159   }
160
161   // Compute derived properties from the register classes
162   computeRegisterProperties(Subtarget->getRegisterInfo());
163
164   // Provide all sorts of operation actions
165   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
166   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
167   setOperationAction(ISD::SETCC, MVT::i32, Custom);
168   setOperationAction(ISD::SETCC, MVT::i64, Custom);
169   setOperationAction(ISD::SETCC, MVT::f32, Custom);
170   setOperationAction(ISD::SETCC, MVT::f64, Custom);
171   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
172   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
173   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
174   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
175   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
176   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
177   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
178   setOperationAction(ISD::SELECT, MVT::i32, Custom);
179   setOperationAction(ISD::SELECT, MVT::i64, Custom);
180   setOperationAction(ISD::SELECT, MVT::f32, Custom);
181   setOperationAction(ISD::SELECT, MVT::f64, Custom);
182   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
183   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
184   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
185   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
186   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
187   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
188
189   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
190   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
191   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
192
193   setOperationAction(ISD::FREM, MVT::f32, Expand);
194   setOperationAction(ISD::FREM, MVT::f64, Expand);
195   setOperationAction(ISD::FREM, MVT::f80, Expand);
196
197   // Custom lowering hooks are needed for XOR
198   // to fold it into CSINC/CSINV.
199   setOperationAction(ISD::XOR, MVT::i32, Custom);
200   setOperationAction(ISD::XOR, MVT::i64, Custom);
201
202   // Virtually no operation on f128 is legal, but LLVM can't expand them when
203   // there's a valid register class, so we need custom operations in most cases.
204   setOperationAction(ISD::FABS, MVT::f128, Expand);
205   setOperationAction(ISD::FADD, MVT::f128, Custom);
206   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
207   setOperationAction(ISD::FCOS, MVT::f128, Expand);
208   setOperationAction(ISD::FDIV, MVT::f128, Custom);
209   setOperationAction(ISD::FMA, MVT::f128, Expand);
210   setOperationAction(ISD::FMUL, MVT::f128, Custom);
211   setOperationAction(ISD::FNEG, MVT::f128, Expand);
212   setOperationAction(ISD::FPOW, MVT::f128, Expand);
213   setOperationAction(ISD::FREM, MVT::f128, Expand);
214   setOperationAction(ISD::FRINT, MVT::f128, Expand);
215   setOperationAction(ISD::FSIN, MVT::f128, Expand);
216   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
217   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
218   setOperationAction(ISD::FSUB, MVT::f128, Custom);
219   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
220   setOperationAction(ISD::SETCC, MVT::f128, Custom);
221   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
222   setOperationAction(ISD::SELECT, MVT::f128, Custom);
223   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
224   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
225
226   // Lowering for many of the conversions is actually specified by the non-f128
227   // type. The LowerXXX function will be trivial when f128 isn't involved.
228   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
229   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
230   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
231   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
232   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
233   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
234   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
235   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
236   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
237   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
238   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
239   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
240   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
241   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
242
243   // Variable arguments.
244   setOperationAction(ISD::VASTART, MVT::Other, Custom);
245   setOperationAction(ISD::VAARG, MVT::Other, Custom);
246   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
247   setOperationAction(ISD::VAEND, MVT::Other, Expand);
248
249   // Variable-sized objects.
250   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
251   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
252   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
253
254   // Constant pool entries
255   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
256
257   // BlockAddress
258   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
259
260   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
261   setOperationAction(ISD::ADDC, MVT::i32, Custom);
262   setOperationAction(ISD::ADDE, MVT::i32, Custom);
263   setOperationAction(ISD::SUBC, MVT::i32, Custom);
264   setOperationAction(ISD::SUBE, MVT::i32, Custom);
265   setOperationAction(ISD::ADDC, MVT::i64, Custom);
266   setOperationAction(ISD::ADDE, MVT::i64, Custom);
267   setOperationAction(ISD::SUBC, MVT::i64, Custom);
268   setOperationAction(ISD::SUBE, MVT::i64, Custom);
269
270   // AArch64 lacks both left-rotate and popcount instructions.
271   setOperationAction(ISD::ROTL, MVT::i32, Expand);
272   setOperationAction(ISD::ROTL, MVT::i64, Expand);
273   for (MVT VT : MVT::vector_valuetypes()) {
274     setOperationAction(ISD::ROTL, VT, Expand);
275     setOperationAction(ISD::ROTR, VT, Expand);
276   }
277
278   // AArch64 doesn't have {U|S}MUL_LOHI.
279   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
280   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
281
282   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
283   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
284
285   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
286   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
287   for (MVT VT : MVT::vector_valuetypes()) {
288     setOperationAction(ISD::SDIVREM, VT, Expand);
289     setOperationAction(ISD::UDIVREM, VT, Expand);
290   }
291   setOperationAction(ISD::SREM, MVT::i32, Expand);
292   setOperationAction(ISD::SREM, MVT::i64, Expand);
293   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
294   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
295   setOperationAction(ISD::UREM, MVT::i32, Expand);
296   setOperationAction(ISD::UREM, MVT::i64, Expand);
297
298   // Custom lower Add/Sub/Mul with overflow.
299   setOperationAction(ISD::SADDO, MVT::i32, Custom);
300   setOperationAction(ISD::SADDO, MVT::i64, Custom);
301   setOperationAction(ISD::UADDO, MVT::i32, Custom);
302   setOperationAction(ISD::UADDO, MVT::i64, Custom);
303   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
304   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
305   setOperationAction(ISD::USUBO, MVT::i32, Custom);
306   setOperationAction(ISD::USUBO, MVT::i64, Custom);
307   setOperationAction(ISD::SMULO, MVT::i32, Custom);
308   setOperationAction(ISD::SMULO, MVT::i64, Custom);
309   setOperationAction(ISD::UMULO, MVT::i32, Custom);
310   setOperationAction(ISD::UMULO, MVT::i64, Custom);
311
312   setOperationAction(ISD::FSIN, MVT::f32, Expand);
313   setOperationAction(ISD::FSIN, MVT::f64, Expand);
314   setOperationAction(ISD::FCOS, MVT::f32, Expand);
315   setOperationAction(ISD::FCOS, MVT::f64, Expand);
316   setOperationAction(ISD::FPOW, MVT::f32, Expand);
317   setOperationAction(ISD::FPOW, MVT::f64, Expand);
318   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
319   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
320
321   // f16 is a storage-only type, always promote it to f32.
322   setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
323   setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
324   setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
325   setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
326   setOperationAction(ISD::FADD,        MVT::f16,  Promote);
327   setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
328   setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
329   setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
330   setOperationAction(ISD::FREM,        MVT::f16,  Promote);
331   setOperationAction(ISD::FMA,         MVT::f16,  Promote);
332   setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
333   setOperationAction(ISD::FABS,        MVT::f16,  Promote);
334   setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
335   setOperationAction(ISD::FCOPYSIGN,   MVT::f16,  Promote);
336   setOperationAction(ISD::FCOS,        MVT::f16,  Promote);
337   setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
338   setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
339   setOperationAction(ISD::FPOW,        MVT::f16,  Promote);
340   setOperationAction(ISD::FPOWI,       MVT::f16,  Promote);
341   setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
342   setOperationAction(ISD::FSIN,        MVT::f16,  Promote);
343   setOperationAction(ISD::FSINCOS,     MVT::f16,  Promote);
344   setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
345   setOperationAction(ISD::FEXP,        MVT::f16,  Promote);
346   setOperationAction(ISD::FEXP2,       MVT::f16,  Promote);
347   setOperationAction(ISD::FLOG,        MVT::f16,  Promote);
348   setOperationAction(ISD::FLOG2,       MVT::f16,  Promote);
349   setOperationAction(ISD::FLOG10,      MVT::f16,  Promote);
350   setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
351   setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
352   setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
353   setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
354   setOperationAction(ISD::FMINNAN,     MVT::f16,  Promote);
355   setOperationAction(ISD::FMAXNAN,     MVT::f16,  Promote);
356
357   // v4f16 is also a storage-only type, so promote it to v4f32 when that is
358   // known to be safe.
359   setOperationAction(ISD::FADD, MVT::v4f16, Promote);
360   setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
361   setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
362   setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
363   setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
364   setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
365   AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
366   AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
367   AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
368   AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
369   AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
370   AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
371
372   // Expand all other v4f16 operations.
373   // FIXME: We could generate better code by promoting some operations to
374   // a pair of v4f32s
375   setOperationAction(ISD::FABS, MVT::v4f16, Expand);
376   setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
377   setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
378   setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
379   setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
380   setOperationAction(ISD::FMA, MVT::v4f16, Expand);
381   setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
382   setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
383   setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
384   setOperationAction(ISD::FREM, MVT::v4f16, Expand);
385   setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
386   setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
387   setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
388   setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
389   setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
390   setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
391   setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
392   setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
393   setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
394   setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
395   setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
396   setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
397   setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
398   setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
399   setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
400
401
402   // v8f16 is also a storage-only type, so expand it.
403   setOperationAction(ISD::FABS, MVT::v8f16, Expand);
404   setOperationAction(ISD::FADD, MVT::v8f16, Expand);
405   setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
406   setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
407   setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
408   setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
409   setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
410   setOperationAction(ISD::FMA, MVT::v8f16, Expand);
411   setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
412   setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
413   setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
414   setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
415   setOperationAction(ISD::FREM, MVT::v8f16, Expand);
416   setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
417   setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
418   setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
419   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
420   setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
421   setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
422   setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
423   setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
424   setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
425   setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
426   setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
427   setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
428   setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
429   setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
430   setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
431   setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
432   setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
433
434   // AArch64 has implementations of a lot of rounding-like FP operations.
435   for (MVT Ty : {MVT::f32, MVT::f64}) {
436     setOperationAction(ISD::FFLOOR, Ty, Legal);
437     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
438     setOperationAction(ISD::FCEIL, Ty, Legal);
439     setOperationAction(ISD::FRINT, Ty, Legal);
440     setOperationAction(ISD::FTRUNC, Ty, Legal);
441     setOperationAction(ISD::FROUND, Ty, Legal);
442     setOperationAction(ISD::FMINNUM, Ty, Legal);
443     setOperationAction(ISD::FMAXNUM, Ty, Legal);
444     setOperationAction(ISD::FMINNAN, Ty, Legal);
445     setOperationAction(ISD::FMAXNAN, Ty, Legal);
446   }
447
448   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
449
450   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
451
452   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
453   // This requires the Performance Monitors extension.
454   if (Subtarget->hasPerfMon())
455     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
456
457   if (Subtarget->isTargetMachO()) {
458     // For iOS, we don't want to the normal expansion of a libcall to
459     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
460     // traffic.
461     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
462     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
463   } else {
464     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
465     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
466   }
467
468   // Make floating-point constants legal for the large code model, so they don't
469   // become loads from the constant pool.
470   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
471     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
472     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
473   }
474
475   // AArch64 does not have floating-point extending loads, i1 sign-extending
476   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
477   for (MVT VT : MVT::fp_valuetypes()) {
478     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
479     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
480     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
481     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
482   }
483   for (MVT VT : MVT::integer_valuetypes())
484     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
485
486   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
487   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
488   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
489   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
490   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
491   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
492   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
493
494   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
495   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
496
497   // Indexed loads and stores are supported.
498   for (unsigned im = (unsigned)ISD::PRE_INC;
499        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
500     setIndexedLoadAction(im, MVT::i8, Legal);
501     setIndexedLoadAction(im, MVT::i16, Legal);
502     setIndexedLoadAction(im, MVT::i32, Legal);
503     setIndexedLoadAction(im, MVT::i64, Legal);
504     setIndexedLoadAction(im, MVT::f64, Legal);
505     setIndexedLoadAction(im, MVT::f32, Legal);
506     setIndexedLoadAction(im, MVT::f16, Legal);
507     setIndexedStoreAction(im, MVT::i8, Legal);
508     setIndexedStoreAction(im, MVT::i16, Legal);
509     setIndexedStoreAction(im, MVT::i32, Legal);
510     setIndexedStoreAction(im, MVT::i64, Legal);
511     setIndexedStoreAction(im, MVT::f64, Legal);
512     setIndexedStoreAction(im, MVT::f32, Legal);
513     setIndexedStoreAction(im, MVT::f16, Legal);
514   }
515
516   // Trap.
517   setOperationAction(ISD::TRAP, MVT::Other, Legal);
518
519   // We combine OR nodes for bitfield operations.
520   setTargetDAGCombine(ISD::OR);
521
522   // Vector add and sub nodes may conceal a high-half opportunity.
523   // Also, try to fold ADD into CSINC/CSINV..
524   setTargetDAGCombine(ISD::ADD);
525   setTargetDAGCombine(ISD::SUB);
526   setTargetDAGCombine(ISD::SRL);
527   setTargetDAGCombine(ISD::XOR);
528   setTargetDAGCombine(ISD::SINT_TO_FP);
529   setTargetDAGCombine(ISD::UINT_TO_FP);
530
531   setTargetDAGCombine(ISD::FP_TO_SINT);
532   setTargetDAGCombine(ISD::FP_TO_UINT);
533   setTargetDAGCombine(ISD::FDIV);
534
535   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
536
537   setTargetDAGCombine(ISD::ANY_EXTEND);
538   setTargetDAGCombine(ISD::ZERO_EXTEND);
539   setTargetDAGCombine(ISD::SIGN_EXTEND);
540   setTargetDAGCombine(ISD::BITCAST);
541   setTargetDAGCombine(ISD::CONCAT_VECTORS);
542   setTargetDAGCombine(ISD::STORE);
543   if (Subtarget->supportsAddressTopByteIgnored())
544     setTargetDAGCombine(ISD::LOAD);
545
546   setTargetDAGCombine(ISD::MUL);
547
548   setTargetDAGCombine(ISD::SELECT);
549   setTargetDAGCombine(ISD::VSELECT);
550
551   setTargetDAGCombine(ISD::INTRINSIC_VOID);
552   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
553   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
554
555   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
556   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
557   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
558
559   setStackPointerRegisterToSaveRestore(AArch64::SP);
560
561   setSchedulingPreference(Sched::Hybrid);
562
563   EnableExtLdPromotion = true;
564
565   // Set required alignment.
566   setMinFunctionAlignment(2);
567   // Set preferred alignments.
568   setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
569   setPrefLoopAlignment(STI.getPrefLoopAlignment());
570
571   // Only change the limit for entries in a jump table if specified by
572   // the subtarget, but not at the command line.
573   unsigned MaxJT = STI.getMaximumJumpTableSize();
574   if (MaxJT && getMaximumJumpTableSize() == 0)
575     setMaximumJumpTableSize(MaxJT);
576
577   setHasExtractBitsInsn(true);
578
579   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
580
581   if (Subtarget->hasNEON()) {
582     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
583     // silliness like this:
584     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
585     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
586     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
587     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
588     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
589     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
590     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
591     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
592     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
593     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
594     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
595     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
596     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
597     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
598     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
599     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
600     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
601     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
602     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
603     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
604     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
605     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
606     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
607     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
608     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
609
610     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
611     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
612     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
613     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
614     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
615
616     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
617
618     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
619     // elements smaller than i32, so promote the input to i32 first.
620     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
621     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
622     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
623     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
624     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
625     // -> v8f16 conversions.
626     setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
627     setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
628     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
629     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
630     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
631     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
632     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
633     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
634     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
635     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
636     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
637     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
638     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
639
640     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
641     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
642
643     setOperationAction(ISD::CTTZ,       MVT::v2i8,  Expand);
644     setOperationAction(ISD::CTTZ,       MVT::v4i16, Expand);
645     setOperationAction(ISD::CTTZ,       MVT::v2i32, Expand);
646     setOperationAction(ISD::CTTZ,       MVT::v1i64, Expand);
647     setOperationAction(ISD::CTTZ,       MVT::v16i8, Expand);
648     setOperationAction(ISD::CTTZ,       MVT::v8i16, Expand);
649     setOperationAction(ISD::CTTZ,       MVT::v4i32, Expand);
650     setOperationAction(ISD::CTTZ,       MVT::v2i64, Expand);
651
652     // AArch64 doesn't have MUL.2d:
653     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
654     // Custom handling for some quad-vector types to detect MULL.
655     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
656     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
657     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
658
659     // Vector reductions
660     for (MVT VT : MVT::integer_valuetypes()) {
661       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
662       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
663       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
664       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
665       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
666     }
667     for (MVT VT : MVT::fp_valuetypes()) {
668       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
669       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
670     }
671
672     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
673     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
674     // Likewise, narrowing and extending vector loads/stores aren't handled
675     // directly.
676     for (MVT VT : MVT::vector_valuetypes()) {
677       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
678
679       setOperationAction(ISD::MULHS, VT, Expand);
680       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
681       setOperationAction(ISD::MULHU, VT, Expand);
682       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
683
684       setOperationAction(ISD::BSWAP, VT, Expand);
685
686       for (MVT InnerVT : MVT::vector_valuetypes()) {
687         setTruncStoreAction(VT, InnerVT, Expand);
688         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
689         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
690         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
691       }
692     }
693
694     // AArch64 has implementations of a lot of rounding-like FP operations.
695     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
696       setOperationAction(ISD::FFLOOR, Ty, Legal);
697       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
698       setOperationAction(ISD::FCEIL, Ty, Legal);
699       setOperationAction(ISD::FRINT, Ty, Legal);
700       setOperationAction(ISD::FTRUNC, Ty, Legal);
701       setOperationAction(ISD::FROUND, Ty, Legal);
702     }
703   }
704
705   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
706 }
707
708 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
709   if (VT == MVT::v2f32 || VT == MVT::v4f16) {
710     setOperationAction(ISD::LOAD, VT, Promote);
711     AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
712
713     setOperationAction(ISD::STORE, VT, Promote);
714     AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
715   } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
716     setOperationAction(ISD::LOAD, VT, Promote);
717     AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
718
719     setOperationAction(ISD::STORE, VT, Promote);
720     AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
721   }
722
723   // Mark vector float intrinsics as expand.
724   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
725     setOperationAction(ISD::FSIN, VT, Expand);
726     setOperationAction(ISD::FCOS, VT, Expand);
727     setOperationAction(ISD::FPOW, VT, Expand);
728     setOperationAction(ISD::FLOG, VT, Expand);
729     setOperationAction(ISD::FLOG2, VT, Expand);
730     setOperationAction(ISD::FLOG10, VT, Expand);
731     setOperationAction(ISD::FEXP, VT, Expand);
732     setOperationAction(ISD::FEXP2, VT, Expand);
733
734     // But we do support custom-lowering for FCOPYSIGN.
735     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
736   }
737
738   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
739   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
740   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
741   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
742   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
743   setOperationAction(ISD::SRA, VT, Custom);
744   setOperationAction(ISD::SRL, VT, Custom);
745   setOperationAction(ISD::SHL, VT, Custom);
746   setOperationAction(ISD::AND, VT, Custom);
747   setOperationAction(ISD::OR, VT, Custom);
748   setOperationAction(ISD::SETCC, VT, Custom);
749   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
750
751   setOperationAction(ISD::SELECT, VT, Expand);
752   setOperationAction(ISD::SELECT_CC, VT, Expand);
753   setOperationAction(ISD::VSELECT, VT, Expand);
754   for (MVT InnerVT : MVT::all_valuetypes())
755     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
756
757   // CNT supports only B element sizes.
758   if (VT != MVT::v8i8 && VT != MVT::v16i8)
759     setOperationAction(ISD::CTPOP, VT, Expand);
760
761   setOperationAction(ISD::UDIV, VT, Expand);
762   setOperationAction(ISD::SDIV, VT, Expand);
763   setOperationAction(ISD::UREM, VT, Expand);
764   setOperationAction(ISD::SREM, VT, Expand);
765   setOperationAction(ISD::FREM, VT, Expand);
766
767   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
768   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
769
770   if (!VT.isFloatingPoint())
771     setOperationAction(ISD::ABS, VT, Legal);
772
773   // [SU][MIN|MAX] are available for all NEON types apart from i64.
774   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
775     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
776       setOperationAction(Opcode, VT, Legal);
777
778   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
779   if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
780     for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
781                             ISD::FMINNUM, ISD::FMAXNUM})
782       setOperationAction(Opcode, VT, Legal);
783
784   if (Subtarget->isLittleEndian()) {
785     for (unsigned im = (unsigned)ISD::PRE_INC;
786          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
787       setIndexedLoadAction(im, VT, Legal);
788       setIndexedStoreAction(im, VT, Legal);
789     }
790   }
791 }
792
793 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
794   addRegisterClass(VT, &AArch64::FPR64RegClass);
795   addTypeForNEON(VT, MVT::v2i32);
796 }
797
798 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
799   addRegisterClass(VT, &AArch64::FPR128RegClass);
800   addTypeForNEON(VT, MVT::v4i32);
801 }
802
803 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
804                                               EVT VT) const {
805   if (!VT.isVector())
806     return MVT::i32;
807   return VT.changeVectorElementTypeToInteger();
808 }
809
810 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
811                                const APInt &Demanded,
812                                TargetLowering::TargetLoweringOpt &TLO,
813                                unsigned NewOpc) {
814   uint64_t OldImm = Imm, NewImm, Enc;
815   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
816
817   // Return if the immediate is already all zeros, all ones, a bimm32 or a
818   // bimm64.
819   if (Imm == 0 || Imm == Mask ||
820       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
821     return false;
822
823   unsigned EltSize = Size;
824   uint64_t DemandedBits = Demanded.getZExtValue();
825
826   // Clear bits that are not demanded.
827   Imm &= DemandedBits;
828
829   while (true) {
830     // The goal here is to set the non-demanded bits in a way that minimizes
831     // the number of switching between 0 and 1. In order to achieve this goal,
832     // we set the non-demanded bits to the value of the preceding demanded bits.
833     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
834     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
835     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
836     // The final result is 0b11000011.
837     uint64_t NonDemandedBits = ~DemandedBits;
838     uint64_t InvertedImm = ~Imm & DemandedBits;
839     uint64_t RotatedImm =
840         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
841         NonDemandedBits;
842     uint64_t Sum = RotatedImm + NonDemandedBits;
843     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
844     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
845     NewImm = (Imm | Ones) & Mask;
846
847     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
848     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
849     // we halve the element size and continue the search.
850     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
851       break;
852
853     // We cannot shrink the element size any further if it is 2-bits.
854     if (EltSize == 2)
855       return false;
856
857     EltSize /= 2;
858     Mask >>= EltSize;
859     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
860
861     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
862     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
863       return false;
864
865     // Merge the upper and lower halves of Imm and DemandedBits.
866     Imm |= Hi;
867     DemandedBits |= DemandedBitsHi;
868   }
869
870   ++NumOptimizedImms;
871
872   // Replicate the element across the register width.
873   while (EltSize < Size) {
874     NewImm |= NewImm << EltSize;
875     EltSize *= 2;
876   }
877
878   (void)OldImm;
879   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
880          "demanded bits should never be altered");
881   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
882
883   // Create the new constant immediate node.
884   EVT VT = Op.getValueType();
885   SDLoc DL(Op);
886   SDValue New;
887
888   // If the new constant immediate is all-zeros or all-ones, let the target
889   // independent DAG combine optimize this node.
890   if (NewImm == 0 || NewImm == OrigMask) {
891     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
892                           TLO.DAG.getConstant(NewImm, DL, VT));
893   // Otherwise, create a machine node so that target independent DAG combine
894   // doesn't undo this optimization.
895   } else {
896     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
897     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
898     New = SDValue(
899         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
900   }
901
902   return TLO.CombineTo(Op, New);
903 }
904
905 bool AArch64TargetLowering::targetShrinkDemandedConstant(
906     SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
907   // Delay this optimization to as late as possible.
908   if (!TLO.LegalOps)
909     return false;
910
911   if (!EnableOptimizeLogicalImm)
912     return false;
913
914   EVT VT = Op.getValueType();
915   if (VT.isVector())
916     return false;
917
918   unsigned Size = VT.getSizeInBits();
919   assert((Size == 32 || Size == 64) &&
920          "i32 or i64 is expected after legalization.");
921
922   // Exit early if we demand all bits.
923   if (Demanded.countPopulation() == Size)
924     return false;
925
926   unsigned NewOpc;
927   switch (Op.getOpcode()) {
928   default:
929     return false;
930   case ISD::AND:
931     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
932     break;
933   case ISD::OR:
934     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
935     break;
936   case ISD::XOR:
937     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
938     break;
939   }
940   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
941   if (!C)
942     return false;
943   uint64_t Imm = C->getZExtValue();
944   return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
945 }
946
947 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
948 /// Mask are known to be either zero or one and return them Known.
949 void AArch64TargetLowering::computeKnownBitsForTargetNode(
950     const SDValue Op, KnownBits &Known,
951     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
952   switch (Op.getOpcode()) {
953   default:
954     break;
955   case AArch64ISD::CSEL: {
956     KnownBits Known2;
957     DAG.computeKnownBits(Op->getOperand(0), Known, Depth + 1);
958     DAG.computeKnownBits(Op->getOperand(1), Known2, Depth + 1);
959     Known.Zero &= Known2.Zero;
960     Known.One &= Known2.One;
961     break;
962   }
963   case ISD::INTRINSIC_W_CHAIN: {
964     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
965     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
966     switch (IntID) {
967     default: return;
968     case Intrinsic::aarch64_ldaxr:
969     case Intrinsic::aarch64_ldxr: {
970       unsigned BitWidth = Known.getBitWidth();
971       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
972       unsigned MemBits = VT.getScalarSizeInBits();
973       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
974       return;
975     }
976     }
977     break;
978   }
979   case ISD::INTRINSIC_WO_CHAIN:
980   case ISD::INTRINSIC_VOID: {
981     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
982     switch (IntNo) {
983     default:
984       break;
985     case Intrinsic::aarch64_neon_umaxv:
986     case Intrinsic::aarch64_neon_uminv: {
987       // Figure out the datatype of the vector operand. The UMINV instruction
988       // will zero extend the result, so we can mark as known zero all the
989       // bits larger than the element datatype. 32-bit or larget doesn't need
990       // this as those are legal types and will be handled by isel directly.
991       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
992       unsigned BitWidth = Known.getBitWidth();
993       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
994         assert(BitWidth >= 8 && "Unexpected width!");
995         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
996         Known.Zero |= Mask;
997       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
998         assert(BitWidth >= 16 && "Unexpected width!");
999         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1000         Known.Zero |= Mask;
1001       }
1002       break;
1003     } break;
1004     }
1005   }
1006   }
1007 }
1008
1009 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1010                                                   EVT) const {
1011   return MVT::i64;
1012 }
1013
1014 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1015                                                            unsigned AddrSpace,
1016                                                            unsigned Align,
1017                                                            bool *Fast) const {
1018   if (Subtarget->requiresStrictAlign())
1019     return false;
1020
1021   if (Fast) {
1022     // Some CPUs are fine with unaligned stores except for 128-bit ones.
1023     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1024             // See comments in performSTORECombine() for more details about
1025             // these conditions.
1026
1027             // Code that uses clang vector extensions can mark that it
1028             // wants unaligned accesses to be treated as fast by
1029             // underspecifying alignment to be 1 or 2.
1030             Align <= 2 ||
1031
1032             // Disregard v2i64. Memcpy lowering produces those and splitting
1033             // them regresses performance on micro-benchmarks and olden/bh.
1034             VT == MVT::v2i64;
1035   }
1036   return true;
1037 }
1038
1039 FastISel *
1040 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1041                                       const TargetLibraryInfo *libInfo) const {
1042   return AArch64::createFastISel(funcInfo, libInfo);
1043 }
1044
1045 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1046   switch ((AArch64ISD::NodeType)Opcode) {
1047   case AArch64ISD::FIRST_NUMBER:      break;
1048   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
1049   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
1050   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
1051   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
1052   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
1053   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
1054   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
1055   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
1056   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
1057   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
1058   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
1059   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
1060   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
1061   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
1062   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
1063   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
1064   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
1065   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
1066   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
1067   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
1068   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
1069   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
1070   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
1071   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
1072   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
1073   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
1074   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
1075   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
1076   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
1077   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
1078   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
1079   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
1080   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
1081   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
1082   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
1083   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
1084   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
1085   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
1086   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
1087   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
1088   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
1089   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
1090   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
1091   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
1092   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
1093   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
1094   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
1095   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
1096   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
1097   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
1098   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
1099   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
1100   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
1101   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
1102   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
1103   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
1104   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
1105   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
1106   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
1107   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
1108   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
1109   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
1110   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
1111   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
1112   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
1113   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
1114   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
1115   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
1116   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
1117   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
1118   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
1119   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
1120   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
1121   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
1122   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
1123   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
1124   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
1125   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
1126   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
1127   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
1128   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
1129   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
1130   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
1131   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
1132   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
1133   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
1134   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
1135   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
1136   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
1137   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
1138   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
1139   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
1140   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
1141   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
1142   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
1143   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
1144   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
1145   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
1146   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
1147   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
1148   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
1149   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
1150   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
1151   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
1152   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
1153   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
1154   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
1155   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
1156   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
1157   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
1158   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
1159   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
1160   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
1161   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
1162   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
1163   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
1164   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
1165   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
1166   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
1167   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
1168   case AArch64ISD::FRECPE:            return "AArch64ISD::FRECPE";
1169   case AArch64ISD::FRECPS:            return "AArch64ISD::FRECPS";
1170   case AArch64ISD::FRSQRTE:           return "AArch64ISD::FRSQRTE";
1171   case AArch64ISD::FRSQRTS:           return "AArch64ISD::FRSQRTS";
1172   }
1173   return nullptr;
1174 }
1175
1176 MachineBasicBlock *
1177 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1178                                     MachineBasicBlock *MBB) const {
1179   // We materialise the F128CSEL pseudo-instruction as some control flow and a
1180   // phi node:
1181
1182   // OrigBB:
1183   //     [... previous instrs leading to comparison ...]
1184   //     b.ne TrueBB
1185   //     b EndBB
1186   // TrueBB:
1187   //     ; Fallthrough
1188   // EndBB:
1189   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1190
1191   MachineFunction *MF = MBB->getParent();
1192   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1193   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1194   DebugLoc DL = MI.getDebugLoc();
1195   MachineFunction::iterator It = ++MBB->getIterator();
1196
1197   unsigned DestReg = MI.getOperand(0).getReg();
1198   unsigned IfTrueReg = MI.getOperand(1).getReg();
1199   unsigned IfFalseReg = MI.getOperand(2).getReg();
1200   unsigned CondCode = MI.getOperand(3).getImm();
1201   bool NZCVKilled = MI.getOperand(4).isKill();
1202
1203   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1204   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1205   MF->insert(It, TrueBB);
1206   MF->insert(It, EndBB);
1207
1208   // Transfer rest of current basic-block to EndBB
1209   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1210                 MBB->end());
1211   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1212
1213   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1214   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1215   MBB->addSuccessor(TrueBB);
1216   MBB->addSuccessor(EndBB);
1217
1218   // TrueBB falls through to the end.
1219   TrueBB->addSuccessor(EndBB);
1220
1221   if (!NZCVKilled) {
1222     TrueBB->addLiveIn(AArch64::NZCV);
1223     EndBB->addLiveIn(AArch64::NZCV);
1224   }
1225
1226   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1227       .addReg(IfTrueReg)
1228       .addMBB(TrueBB)
1229       .addReg(IfFalseReg)
1230       .addMBB(MBB);
1231
1232   MI.eraseFromParent();
1233   return EndBB;
1234 }
1235
1236 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1237     MachineInstr &MI, MachineBasicBlock *BB) const {
1238   switch (MI.getOpcode()) {
1239   default:
1240 #ifndef NDEBUG
1241     MI.dump();
1242 #endif
1243     llvm_unreachable("Unexpected instruction for custom inserter!");
1244
1245   case AArch64::F128CSEL:
1246     return EmitF128CSEL(MI, BB);
1247
1248   case TargetOpcode::STACKMAP:
1249   case TargetOpcode::PATCHPOINT:
1250     return emitPatchPoint(MI, BB);
1251   }
1252 }
1253
1254 //===----------------------------------------------------------------------===//
1255 // AArch64 Lowering private implementation.
1256 //===----------------------------------------------------------------------===//
1257
1258 //===----------------------------------------------------------------------===//
1259 // Lowering Code
1260 //===----------------------------------------------------------------------===//
1261
1262 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1263 /// CC
1264 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1265   switch (CC) {
1266   default:
1267     llvm_unreachable("Unknown condition code!");
1268   case ISD::SETNE:
1269     return AArch64CC::NE;
1270   case ISD::SETEQ:
1271     return AArch64CC::EQ;
1272   case ISD::SETGT:
1273     return AArch64CC::GT;
1274   case ISD::SETGE:
1275     return AArch64CC::GE;
1276   case ISD::SETLT:
1277     return AArch64CC::LT;
1278   case ISD::SETLE:
1279     return AArch64CC::LE;
1280   case ISD::SETUGT:
1281     return AArch64CC::HI;
1282   case ISD::SETUGE:
1283     return AArch64CC::HS;
1284   case ISD::SETULT:
1285     return AArch64CC::LO;
1286   case ISD::SETULE:
1287     return AArch64CC::LS;
1288   }
1289 }
1290
1291 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1292 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1293                                   AArch64CC::CondCode &CondCode,
1294                                   AArch64CC::CondCode &CondCode2) {
1295   CondCode2 = AArch64CC::AL;
1296   switch (CC) {
1297   default:
1298     llvm_unreachable("Unknown FP condition!");
1299   case ISD::SETEQ:
1300   case ISD::SETOEQ:
1301     CondCode = AArch64CC::EQ;
1302     break;
1303   case ISD::SETGT:
1304   case ISD::SETOGT:
1305     CondCode = AArch64CC::GT;
1306     break;
1307   case ISD::SETGE:
1308   case ISD::SETOGE:
1309     CondCode = AArch64CC::GE;
1310     break;
1311   case ISD::SETOLT:
1312     CondCode = AArch64CC::MI;
1313     break;
1314   case ISD::SETOLE:
1315     CondCode = AArch64CC::LS;
1316     break;
1317   case ISD::SETONE:
1318     CondCode = AArch64CC::MI;
1319     CondCode2 = AArch64CC::GT;
1320     break;
1321   case ISD::SETO:
1322     CondCode = AArch64CC::VC;
1323     break;
1324   case ISD::SETUO:
1325     CondCode = AArch64CC::VS;
1326     break;
1327   case ISD::SETUEQ:
1328     CondCode = AArch64CC::EQ;
1329     CondCode2 = AArch64CC::VS;
1330     break;
1331   case ISD::SETUGT:
1332     CondCode = AArch64CC::HI;
1333     break;
1334   case ISD::SETUGE:
1335     CondCode = AArch64CC::PL;
1336     break;
1337   case ISD::SETLT:
1338   case ISD::SETULT:
1339     CondCode = AArch64CC::LT;
1340     break;
1341   case ISD::SETLE:
1342   case ISD::SETULE:
1343     CondCode = AArch64CC::LE;
1344     break;
1345   case ISD::SETNE:
1346   case ISD::SETUNE:
1347     CondCode = AArch64CC::NE;
1348     break;
1349   }
1350 }
1351
1352 /// Convert a DAG fp condition code to an AArch64 CC.
1353 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1354 /// should be AND'ed instead of OR'ed.
1355 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1356                                      AArch64CC::CondCode &CondCode,
1357                                      AArch64CC::CondCode &CondCode2) {
1358   CondCode2 = AArch64CC::AL;
1359   switch (CC) {
1360   default:
1361     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1362     assert(CondCode2 == AArch64CC::AL);
1363     break;
1364   case ISD::SETONE:
1365     // (a one b)
1366     // == ((a olt b) || (a ogt b))
1367     // == ((a ord b) && (a une b))
1368     CondCode = AArch64CC::VC;
1369     CondCode2 = AArch64CC::NE;
1370     break;
1371   case ISD::SETUEQ:
1372     // (a ueq b)
1373     // == ((a uno b) || (a oeq b))
1374     // == ((a ule b) && (a uge b))
1375     CondCode = AArch64CC::PL;
1376     CondCode2 = AArch64CC::LE;
1377     break;
1378   }
1379 }
1380
1381 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1382 /// CC usable with the vector instructions. Fewer operations are available
1383 /// without a real NZCV register, so we have to use less efficient combinations
1384 /// to get the same effect.
1385 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1386                                         AArch64CC::CondCode &CondCode,
1387                                         AArch64CC::CondCode &CondCode2,
1388                                         bool &Invert) {
1389   Invert = false;
1390   switch (CC) {
1391   default:
1392     // Mostly the scalar mappings work fine.
1393     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1394     break;
1395   case ISD::SETUO:
1396     Invert = true;
1397     LLVM_FALLTHROUGH;
1398   case ISD::SETO:
1399     CondCode = AArch64CC::MI;
1400     CondCode2 = AArch64CC::GE;
1401     break;
1402   case ISD::SETUEQ:
1403   case ISD::SETULT:
1404   case ISD::SETULE:
1405   case ISD::SETUGT:
1406   case ISD::SETUGE:
1407     // All of the compare-mask comparisons are ordered, but we can switch
1408     // between the two by a double inversion. E.g. ULE == !OGT.
1409     Invert = true;
1410     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1411     break;
1412   }
1413 }
1414
1415 static bool isLegalArithImmed(uint64_t C) {
1416   // Matches AArch64DAGToDAGISel::SelectArithImmed().
1417   return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1418 }
1419
1420 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1421                               const SDLoc &dl, SelectionDAG &DAG) {
1422   EVT VT = LHS.getValueType();
1423
1424   if (VT.isFloatingPoint()) {
1425     assert(VT != MVT::f128);
1426     if (VT == MVT::f16) {
1427       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1428       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1429       VT = MVT::f32;
1430     }
1431     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1432   }
1433
1434   // The CMP instruction is just an alias for SUBS, and representing it as
1435   // SUBS means that it's possible to get CSE with subtract operations.
1436   // A later phase can perform the optimization of setting the destination
1437   // register to WZR/XZR if it ends up being unused.
1438   unsigned Opcode = AArch64ISD::SUBS;
1439
1440   if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
1441       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1442     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1443     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1444     // can be set differently by this operation. It comes down to whether
1445     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1446     // everything is fine. If not then the optimization is wrong. Thus general
1447     // comparisons are only valid if op2 != 0.
1448
1449     // So, finally, the only LLVM-native comparisons that don't mention C and V
1450     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1451     // the absence of information about op2.
1452     Opcode = AArch64ISD::ADDS;
1453     RHS = RHS.getOperand(1);
1454   } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1455              !isUnsignedIntSetCC(CC)) {
1456     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1457     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1458     // of the signed comparisons.
1459     Opcode = AArch64ISD::ANDS;
1460     RHS = LHS.getOperand(1);
1461     LHS = LHS.getOperand(0);
1462   }
1463
1464   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1465       .getValue(1);
1466 }
1467
1468 /// \defgroup AArch64CCMP CMP;CCMP matching
1469 ///
1470 /// These functions deal with the formation of CMP;CCMP;... sequences.
1471 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1472 /// a comparison. They set the NZCV flags to a predefined value if their
1473 /// predicate is false. This allows to express arbitrary conjunctions, for
1474 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1475 /// expressed as:
1476 ///   cmp A
1477 ///   ccmp B, inv(CB), CA
1478 ///   check for CB flags
1479 ///
1480 /// In general we can create code for arbitrary "... (and (and A B) C)"
1481 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1482 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1483 /// negation operations:
1484 /// We can negate the results of a single comparison by inverting the flags
1485 /// used when the predicate fails and inverting the flags tested in the next
1486 /// instruction; We can also negate the results of the whole previous
1487 /// conditional compare sequence by inverting the flags tested in the next
1488 /// instruction. However there is no way to negate the result of a partial
1489 /// sequence.
1490 ///
1491 /// Therefore on encountering an "or" expression we can negate the subtree on
1492 /// one side and have to be able to push the negate to the leafs of the subtree
1493 /// on the other side (see also the comments in code). As complete example:
1494 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1495 ///     (and (setCC (cmp C)) (setCD (cmp D)))"
1496 /// is transformed to
1497 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1498 ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1499 /// and implemented as:
1500 ///   cmp C
1501 ///   ccmp D, inv(CD), CC
1502 ///   ccmp A, CA, inv(CD)
1503 ///   ccmp B, CB, inv(CA)
1504 ///   check for CB flags
1505 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1506 /// by conditional compare sequences.
1507 /// @{
1508
1509 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1510 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1511                                          ISD::CondCode CC, SDValue CCOp,
1512                                          AArch64CC::CondCode Predicate,
1513                                          AArch64CC::CondCode OutCC,
1514                                          const SDLoc &DL, SelectionDAG &DAG) {
1515   unsigned Opcode = 0;
1516   if (LHS.getValueType().isFloatingPoint()) {
1517     assert(LHS.getValueType() != MVT::f128);
1518     if (LHS.getValueType() == MVT::f16) {
1519       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1520       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1521     }
1522     Opcode = AArch64ISD::FCCMP;
1523   } else if (RHS.getOpcode() == ISD::SUB) {
1524     SDValue SubOp0 = RHS.getOperand(0);
1525     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1526       // See emitComparison() on why we can only do this for SETEQ and SETNE.
1527       Opcode = AArch64ISD::CCMN;
1528       RHS = RHS.getOperand(1);
1529     }
1530   }
1531   if (Opcode == 0)
1532     Opcode = AArch64ISD::CCMP;
1533
1534   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1535   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1536   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1537   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1538   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1539 }
1540
1541 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1542 /// CanPushNegate is set to true if we can push a negate operation through
1543 /// the tree in a was that we are left with AND operations and negate operations
1544 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1545 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1546 /// brought into such a form.
1547 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
1548                                          unsigned Depth = 0) {
1549   if (!Val.hasOneUse())
1550     return false;
1551   unsigned Opcode = Val->getOpcode();
1552   if (Opcode == ISD::SETCC) {
1553     if (Val->getOperand(0).getValueType() == MVT::f128)
1554       return false;
1555     CanNegate = true;
1556     return true;
1557   }
1558   // Protect against exponential runtime and stack overflow.
1559   if (Depth > 6)
1560     return false;
1561   if (Opcode == ISD::AND || Opcode == ISD::OR) {
1562     SDValue O0 = Val->getOperand(0);
1563     SDValue O1 = Val->getOperand(1);
1564     bool CanNegateL;
1565     if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
1566       return false;
1567     bool CanNegateR;
1568     if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
1569       return false;
1570
1571     if (Opcode == ISD::OR) {
1572       // For an OR expression we need to be able to negate at least one side or
1573       // we cannot do the transformation at all.
1574       if (!CanNegateL && !CanNegateR)
1575         return false;
1576       // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1577       // can negate the x and y subtrees.
1578       CanNegate = CanNegateL && CanNegateR;
1579     } else {
1580       // If the operands are OR expressions then we finally need to negate their
1581       // outputs, we can only do that for the operand with emitted last by
1582       // negating OutCC, not for both operands.
1583       bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1584       bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1585       if (NeedsNegOutL && NeedsNegOutR)
1586         return false;
1587       // We cannot negate an AND operation (it would become an OR),
1588       CanNegate = false;
1589     }
1590     return true;
1591   }
1592   return false;
1593 }
1594
1595 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1596 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1597 /// Tries to transform the given i1 producing node @p Val to a series compare
1598 /// and conditional compare operations. @returns an NZCV flags producing node
1599 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1600 /// transformation was not possible.
1601 /// On recursive invocations @p PushNegate may be set to true to have negation
1602 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1603 /// for the comparisons in the current subtree; @p Depth limits the search
1604 /// depth to avoid stack overflow.
1605 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1606     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1607     AArch64CC::CondCode Predicate) {
1608   // We're at a tree leaf, produce a conditional comparison operation.
1609   unsigned Opcode = Val->getOpcode();
1610   if (Opcode == ISD::SETCC) {
1611     SDValue LHS = Val->getOperand(0);
1612     SDValue RHS = Val->getOperand(1);
1613     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1614     bool isInteger = LHS.getValueType().isInteger();
1615     if (Negate)
1616       CC = getSetCCInverse(CC, isInteger);
1617     SDLoc DL(Val);
1618     // Determine OutCC and handle FP special case.
1619     if (isInteger) {
1620       OutCC = changeIntCCToAArch64CC(CC);
1621     } else {
1622       assert(LHS.getValueType().isFloatingPoint());
1623       AArch64CC::CondCode ExtraCC;
1624       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1625       // Some floating point conditions can't be tested with a single condition
1626       // code. Construct an additional comparison in this case.
1627       if (ExtraCC != AArch64CC::AL) {
1628         SDValue ExtraCmp;
1629         if (!CCOp.getNode())
1630           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1631         else
1632           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1633                                                ExtraCC, DL, DAG);
1634         CCOp = ExtraCmp;
1635         Predicate = ExtraCC;
1636       }
1637     }
1638
1639     // Produce a normal comparison if we are first in the chain
1640     if (!CCOp)
1641       return emitComparison(LHS, RHS, CC, DL, DAG);
1642     // Otherwise produce a ccmp.
1643     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1644                                      DAG);
1645   }
1646   assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1647          "Valid conjunction/disjunction tree");
1648
1649   // Check if both sides can be transformed.
1650   SDValue LHS = Val->getOperand(0);
1651   SDValue RHS = Val->getOperand(1);
1652
1653   // In case of an OR we need to negate our operands and the result.
1654   // (A v B) <=> not(not(A) ^ not(B))
1655   bool NegateOpsAndResult = Opcode == ISD::OR;
1656   // We can negate the results of all previous operations by inverting the
1657   // predicate flags giving us a free negation for one side. The other side
1658   // must be negatable by itself.
1659   if (NegateOpsAndResult) {
1660     // See which side we can negate.
1661     bool CanNegateL;
1662     bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1663     assert(isValidL && "Valid conjunction/disjunction tree");
1664     (void)isValidL;
1665
1666 #ifndef NDEBUG
1667     bool CanNegateR;
1668     bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1669     assert(isValidR && "Valid conjunction/disjunction tree");
1670     assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1671 #endif
1672
1673     // Order the side which we cannot negate to RHS so we can emit it first.
1674     if (!CanNegateL)
1675       std::swap(LHS, RHS);
1676   } else {
1677     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1678     assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
1679            "Valid conjunction/disjunction tree");
1680     // Order the side where we need to negate the output flags to RHS so it
1681     // gets emitted first.
1682     if (NeedsNegOutL)
1683       std::swap(LHS, RHS);
1684   }
1685
1686   // Emit RHS. If we want to negate the tree we only need to push a negate
1687   // through if we are already in a PushNegate case, otherwise we can negate
1688   // the "flags to test" afterwards.
1689   AArch64CC::CondCode RHSCC;
1690   SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1691                                                    CCOp, Predicate);
1692   if (NegateOpsAndResult && !Negate)
1693     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1694   // Emit LHS. We may need to negate it.
1695   SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1696                                                    NegateOpsAndResult, CmpR,
1697                                                    RHSCC);
1698   // If we transformed an OR to and AND then we have to negate the result
1699   // (or absorb the Negate parameter).
1700   if (NegateOpsAndResult && !Negate)
1701     OutCC = AArch64CC::getInvertedCondCode(OutCC);
1702   return CmpL;
1703 }
1704
1705 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1706 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1707 /// \see emitConjunctionDisjunctionTreeRec().
1708 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1709                                               AArch64CC::CondCode &OutCC) {
1710   bool CanNegate;
1711   if (!isConjunctionDisjunctionTree(Val, CanNegate))
1712     return SDValue();
1713
1714   return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1715                                            AArch64CC::AL);
1716 }
1717
1718 /// @}
1719
1720 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1721                              SDValue &AArch64cc, SelectionDAG &DAG,
1722                              const SDLoc &dl) {
1723   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1724     EVT VT = RHS.getValueType();
1725     uint64_t C = RHSC->getZExtValue();
1726     if (!isLegalArithImmed(C)) {
1727       // Constant does not fit, try adjusting it by one?
1728       switch (CC) {
1729       default:
1730         break;
1731       case ISD::SETLT:
1732       case ISD::SETGE:
1733         if ((VT == MVT::i32 && C != 0x80000000 &&
1734              isLegalArithImmed((uint32_t)(C - 1))) ||
1735             (VT == MVT::i64 && C != 0x80000000ULL &&
1736              isLegalArithImmed(C - 1ULL))) {
1737           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1738           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1739           RHS = DAG.getConstant(C, dl, VT);
1740         }
1741         break;
1742       case ISD::SETULT:
1743       case ISD::SETUGE:
1744         if ((VT == MVT::i32 && C != 0 &&
1745              isLegalArithImmed((uint32_t)(C - 1))) ||
1746             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1747           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1748           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1749           RHS = DAG.getConstant(C, dl, VT);
1750         }
1751         break;
1752       case ISD::SETLE:
1753       case ISD::SETGT:
1754         if ((VT == MVT::i32 && C != INT32_MAX &&
1755              isLegalArithImmed((uint32_t)(C + 1))) ||
1756             (VT == MVT::i64 && C != INT64_MAX &&
1757              isLegalArithImmed(C + 1ULL))) {
1758           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1759           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1760           RHS = DAG.getConstant(C, dl, VT);
1761         }
1762         break;
1763       case ISD::SETULE:
1764       case ISD::SETUGT:
1765         if ((VT == MVT::i32 && C != UINT32_MAX &&
1766              isLegalArithImmed((uint32_t)(C + 1))) ||
1767             (VT == MVT::i64 && C != UINT64_MAX &&
1768              isLegalArithImmed(C + 1ULL))) {
1769           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1770           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1771           RHS = DAG.getConstant(C, dl, VT);
1772         }
1773         break;
1774       }
1775     }
1776   }
1777   SDValue Cmp;
1778   AArch64CC::CondCode AArch64CC;
1779   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1780     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1781
1782     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1783     // For the i8 operand, the largest immediate is 255, so this can be easily
1784     // encoded in the compare instruction. For the i16 operand, however, the
1785     // largest immediate cannot be encoded in the compare.
1786     // Therefore, use a sign extending load and cmn to avoid materializing the
1787     // -1 constant. For example,
1788     // movz w1, #65535
1789     // ldrh w0, [x0, #0]
1790     // cmp w0, w1
1791     // >
1792     // ldrsh w0, [x0, #0]
1793     // cmn w0, #1
1794     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1795     // if and only if (sext LHS) == (sext RHS). The checks are in place to
1796     // ensure both the LHS and RHS are truly zero extended and to make sure the
1797     // transformation is profitable.
1798     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1799         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1800         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1801         LHS.getNode()->hasNUsesOfValue(1, 0)) {
1802       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1803       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1804         SDValue SExt =
1805             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1806                         DAG.getValueType(MVT::i16));
1807         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1808                                                    RHS.getValueType()),
1809                              CC, dl, DAG);
1810         AArch64CC = changeIntCCToAArch64CC(CC);
1811       }
1812     }
1813
1814     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1815       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1816         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1817           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1818       }
1819     }
1820   }
1821
1822   if (!Cmp) {
1823     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1824     AArch64CC = changeIntCCToAArch64CC(CC);
1825   }
1826   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1827   return Cmp;
1828 }
1829
1830 static std::pair<SDValue, SDValue>
1831 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1832   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1833          "Unsupported value type");
1834   SDValue Value, Overflow;
1835   SDLoc DL(Op);
1836   SDValue LHS = Op.getOperand(0);
1837   SDValue RHS = Op.getOperand(1);
1838   unsigned Opc = 0;
1839   switch (Op.getOpcode()) {
1840   default:
1841     llvm_unreachable("Unknown overflow instruction!");
1842   case ISD::SADDO:
1843     Opc = AArch64ISD::ADDS;
1844     CC = AArch64CC::VS;
1845     break;
1846   case ISD::UADDO:
1847     Opc = AArch64ISD::ADDS;
1848     CC = AArch64CC::HS;
1849     break;
1850   case ISD::SSUBO:
1851     Opc = AArch64ISD::SUBS;
1852     CC = AArch64CC::VS;
1853     break;
1854   case ISD::USUBO:
1855     Opc = AArch64ISD::SUBS;
1856     CC = AArch64CC::LO;
1857     break;
1858   // Multiply needs a little bit extra work.
1859   case ISD::SMULO:
1860   case ISD::UMULO: {
1861     CC = AArch64CC::NE;
1862     bool IsSigned = Op.getOpcode() == ISD::SMULO;
1863     if (Op.getValueType() == MVT::i32) {
1864       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1865       // For a 32 bit multiply with overflow check we want the instruction
1866       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1867       // need to generate the following pattern:
1868       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1869       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1870       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1871       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1872       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1873                                 DAG.getConstant(0, DL, MVT::i64));
1874       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1875       // operation. We need to clear out the upper 32 bits, because we used a
1876       // widening multiply that wrote all 64 bits. In the end this should be a
1877       // noop.
1878       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1879       if (IsSigned) {
1880         // The signed overflow check requires more than just a simple check for
1881         // any bit set in the upper 32 bits of the result. These bits could be
1882         // just the sign bits of a negative number. To perform the overflow
1883         // check we have to arithmetic shift right the 32nd bit of the result by
1884         // 31 bits. Then we compare the result to the upper 32 bits.
1885         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1886                                         DAG.getConstant(32, DL, MVT::i64));
1887         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1888         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1889                                         DAG.getConstant(31, DL, MVT::i64));
1890         // It is important that LowerBits is last, otherwise the arithmetic
1891         // shift will not be folded into the compare (SUBS).
1892         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1893         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1894                        .getValue(1);
1895       } else {
1896         // The overflow check for unsigned multiply is easy. We only need to
1897         // check if any of the upper 32 bits are set. This can be done with a
1898         // CMP (shifted register). For that we need to generate the following
1899         // pattern:
1900         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1901         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1902                                         DAG.getConstant(32, DL, MVT::i64));
1903         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1904         Overflow =
1905             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1906                         DAG.getConstant(0, DL, MVT::i64),
1907                         UpperBits).getValue(1);
1908       }
1909       break;
1910     }
1911     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1912     // For the 64 bit multiply
1913     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1914     if (IsSigned) {
1915       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1916       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1917                                       DAG.getConstant(63, DL, MVT::i64));
1918       // It is important that LowerBits is last, otherwise the arithmetic
1919       // shift will not be folded into the compare (SUBS).
1920       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1921       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1922                      .getValue(1);
1923     } else {
1924       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1925       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1926       Overflow =
1927           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1928                       DAG.getConstant(0, DL, MVT::i64),
1929                       UpperBits).getValue(1);
1930     }
1931     break;
1932   }
1933   } // switch (...)
1934
1935   if (Opc) {
1936     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1937
1938     // Emit the AArch64 operation with overflow check.
1939     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1940     Overflow = Value.getValue(1);
1941   }
1942   return std::make_pair(Value, Overflow);
1943 }
1944
1945 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1946                                              RTLIB::Libcall Call) const {
1947   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1948   return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1949 }
1950
1951 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1952   SDValue Sel = Op.getOperand(0);
1953   SDValue Other = Op.getOperand(1);
1954
1955   // If neither operand is a SELECT_CC, give up.
1956   if (Sel.getOpcode() != ISD::SELECT_CC)
1957     std::swap(Sel, Other);
1958   if (Sel.getOpcode() != ISD::SELECT_CC)
1959     return Op;
1960
1961   // The folding we want to perform is:
1962   // (xor x, (select_cc a, b, cc, 0, -1) )
1963   //   -->
1964   // (csel x, (xor x, -1), cc ...)
1965   //
1966   // The latter will get matched to a CSINV instruction.
1967
1968   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1969   SDValue LHS = Sel.getOperand(0);
1970   SDValue RHS = Sel.getOperand(1);
1971   SDValue TVal = Sel.getOperand(2);
1972   SDValue FVal = Sel.getOperand(3);
1973   SDLoc dl(Sel);
1974
1975   // FIXME: This could be generalized to non-integer comparisons.
1976   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1977     return Op;
1978
1979   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1980   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1981
1982   // The values aren't constants, this isn't the pattern we're looking for.
1983   if (!CFVal || !CTVal)
1984     return Op;
1985
1986   // We can commute the SELECT_CC by inverting the condition.  This
1987   // might be needed to make this fit into a CSINV pattern.
1988   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1989     std::swap(TVal, FVal);
1990     std::swap(CTVal, CFVal);
1991     CC = ISD::getSetCCInverse(CC, true);
1992   }
1993
1994   // If the constants line up, perform the transform!
1995   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1996     SDValue CCVal;
1997     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1998
1999     FVal = Other;
2000     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2001                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
2002
2003     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2004                        CCVal, Cmp);
2005   }
2006
2007   return Op;
2008 }
2009
2010 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2011   EVT VT = Op.getValueType();
2012
2013   // Let legalize expand this if it isn't a legal type yet.
2014   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2015     return SDValue();
2016
2017   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2018
2019   unsigned Opc;
2020   bool ExtraOp = false;
2021   switch (Op.getOpcode()) {
2022   default:
2023     llvm_unreachable("Invalid code");
2024   case ISD::ADDC:
2025     Opc = AArch64ISD::ADDS;
2026     break;
2027   case ISD::SUBC:
2028     Opc = AArch64ISD::SUBS;
2029     break;
2030   case ISD::ADDE:
2031     Opc = AArch64ISD::ADCS;
2032     ExtraOp = true;
2033     break;
2034   case ISD::SUBE:
2035     Opc = AArch64ISD::SBCS;
2036     ExtraOp = true;
2037     break;
2038   }
2039
2040   if (!ExtraOp)
2041     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2042   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2043                      Op.getOperand(2));
2044 }
2045
2046 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2047   // Let legalize expand this if it isn't a legal type yet.
2048   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2049     return SDValue();
2050
2051   SDLoc dl(Op);
2052   AArch64CC::CondCode CC;
2053   // The actual operation that sets the overflow or carry flag.
2054   SDValue Value, Overflow;
2055   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2056
2057   // We use 0 and 1 as false and true values.
2058   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2059   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2060
2061   // We use an inverted condition, because the conditional select is inverted
2062   // too. This will allow it to be selected to a single instruction:
2063   // CSINC Wd, WZR, WZR, invert(cond).
2064   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2065   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2066                          CCVal, Overflow);
2067
2068   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2069   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2070 }
2071
2072 // Prefetch operands are:
2073 // 1: Address to prefetch
2074 // 2: bool isWrite
2075 // 3: int locality (0 = no locality ... 3 = extreme locality)
2076 // 4: bool isDataCache
2077 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2078   SDLoc DL(Op);
2079   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2080   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2081   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2082
2083   bool IsStream = !Locality;
2084   // When the locality number is set
2085   if (Locality) {
2086     // The front-end should have filtered out the out-of-range values
2087     assert(Locality <= 3 && "Prefetch locality out-of-range");
2088     // The locality degree is the opposite of the cache speed.
2089     // Put the number the other way around.
2090     // The encoding starts at 0 for level 1
2091     Locality = 3 - Locality;
2092   }
2093
2094   // built the mask value encoding the expected behavior.
2095   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
2096                    (!IsData << 3) |     // IsDataCache bit
2097                    (Locality << 1) |    // Cache level bits
2098                    (unsigned)IsStream;  // Stream bit
2099   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2100                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2101 }
2102
2103 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2104                                               SelectionDAG &DAG) const {
2105   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2106
2107   RTLIB::Libcall LC;
2108   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2109
2110   return LowerF128Call(Op, DAG, LC);
2111 }
2112
2113 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2114                                              SelectionDAG &DAG) const {
2115   if (Op.getOperand(0).getValueType() != MVT::f128) {
2116     // It's legal except when f128 is involved
2117     return Op;
2118   }
2119
2120   RTLIB::Libcall LC;
2121   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2122
2123   // FP_ROUND node has a second operand indicating whether it is known to be
2124   // precise. That doesn't take part in the LibCall so we can't directly use
2125   // LowerF128Call.
2126   SDValue SrcVal = Op.getOperand(0);
2127   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2128                      SDLoc(Op)).first;
2129 }
2130
2131 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
2132   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2133   // Any additional optimization in this function should be recorded
2134   // in the cost tables.
2135   EVT InVT = Op.getOperand(0).getValueType();
2136   EVT VT = Op.getValueType();
2137   unsigned NumElts = InVT.getVectorNumElements();
2138
2139   // f16 vectors are promoted to f32 before a conversion.
2140   if (InVT.getVectorElementType() == MVT::f16) {
2141     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2142     SDLoc dl(Op);
2143     return DAG.getNode(
2144         Op.getOpcode(), dl, Op.getValueType(),
2145         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2146   }
2147
2148   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2149     SDLoc dl(Op);
2150     SDValue Cv =
2151         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2152                     Op.getOperand(0));
2153     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2154   }
2155
2156   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2157     SDLoc dl(Op);
2158     MVT ExtVT =
2159         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2160                          VT.getVectorNumElements());
2161     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2162     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2163   }
2164
2165   // Type changing conversions are illegal.
2166   return Op;
2167 }
2168
2169 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2170                                               SelectionDAG &DAG) const {
2171   if (Op.getOperand(0).getValueType().isVector())
2172     return LowerVectorFP_TO_INT(Op, DAG);
2173
2174   // f16 conversions are promoted to f32.
2175   if (Op.getOperand(0).getValueType() == MVT::f16) {
2176     SDLoc dl(Op);
2177     return DAG.getNode(
2178         Op.getOpcode(), dl, Op.getValueType(),
2179         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2180   }
2181
2182   if (Op.getOperand(0).getValueType() != MVT::f128) {
2183     // It's legal except when f128 is involved
2184     return Op;
2185   }
2186
2187   RTLIB::Libcall LC;
2188   if (Op.getOpcode() == ISD::FP_TO_SINT)
2189     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2190   else
2191     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2192
2193   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2194   return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
2195 }
2196
2197 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2198   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2199   // Any additional optimization in this function should be recorded
2200   // in the cost tables.
2201   EVT VT = Op.getValueType();
2202   SDLoc dl(Op);
2203   SDValue In = Op.getOperand(0);
2204   EVT InVT = In.getValueType();
2205
2206   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2207     MVT CastVT =
2208         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2209                          InVT.getVectorNumElements());
2210     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2211     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2212   }
2213
2214   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2215     unsigned CastOpc =
2216         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2217     EVT CastVT = VT.changeVectorElementTypeToInteger();
2218     In = DAG.getNode(CastOpc, dl, CastVT, In);
2219     return DAG.getNode(Op.getOpcode(), dl, VT, In);
2220   }
2221
2222   return Op;
2223 }
2224
2225 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2226                                             SelectionDAG &DAG) const {
2227   if (Op.getValueType().isVector())
2228     return LowerVectorINT_TO_FP(Op, DAG);
2229
2230   // f16 conversions are promoted to f32.
2231   if (Op.getValueType() == MVT::f16) {
2232     SDLoc dl(Op);
2233     return DAG.getNode(
2234         ISD::FP_ROUND, dl, MVT::f16,
2235         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2236         DAG.getIntPtrConstant(0, dl));
2237   }
2238
2239   // i128 conversions are libcalls.
2240   if (Op.getOperand(0).getValueType() == MVT::i128)
2241     return SDValue();
2242
2243   // Other conversions are legal, unless it's to the completely software-based
2244   // fp128.
2245   if (Op.getValueType() != MVT::f128)
2246     return Op;
2247
2248   RTLIB::Libcall LC;
2249   if (Op.getOpcode() == ISD::SINT_TO_FP)
2250     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2251   else
2252     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2253
2254   return LowerF128Call(Op, DAG, LC);
2255 }
2256
2257 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2258                                             SelectionDAG &DAG) const {
2259   // For iOS, we want to call an alternative entry point: __sincos_stret,
2260   // which returns the values in two S / D registers.
2261   SDLoc dl(Op);
2262   SDValue Arg = Op.getOperand(0);
2263   EVT ArgVT = Arg.getValueType();
2264   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2265
2266   ArgListTy Args;
2267   ArgListEntry Entry;
2268
2269   Entry.Node = Arg;
2270   Entry.Ty = ArgTy;
2271   Entry.IsSExt = false;
2272   Entry.IsZExt = false;
2273   Args.push_back(Entry);
2274
2275   const char *LibcallName =
2276       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
2277   SDValue Callee =
2278       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2279
2280   StructType *RetTy = StructType::get(ArgTy, ArgTy);
2281   TargetLowering::CallLoweringInfo CLI(DAG);
2282   CLI.setDebugLoc(dl)
2283       .setChain(DAG.getEntryNode())
2284       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2285
2286   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2287   return CallResult.first;
2288 }
2289
2290 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2291   if (Op.getValueType() != MVT::f16)
2292     return SDValue();
2293
2294   assert(Op.getOperand(0).getValueType() == MVT::i16);
2295   SDLoc DL(Op);
2296
2297   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2298   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2299   return SDValue(
2300       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2301                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2302       0);
2303 }
2304
2305 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2306   if (OrigVT.getSizeInBits() >= 64)
2307     return OrigVT;
2308
2309   assert(OrigVT.isSimple() && "Expecting a simple value type");
2310
2311   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2312   switch (OrigSimpleTy) {
2313   default: llvm_unreachable("Unexpected Vector Type");
2314   case MVT::v2i8:
2315   case MVT::v2i16:
2316      return MVT::v2i32;
2317   case MVT::v4i8:
2318     return  MVT::v4i16;
2319   }
2320 }
2321
2322 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2323                                                  const EVT &OrigTy,
2324                                                  const EVT &ExtTy,
2325                                                  unsigned ExtOpcode) {
2326   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2327   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2328   // 64-bits we need to insert a new extension so that it will be 64-bits.
2329   assert(ExtTy.is128BitVector() && "Unexpected extension size");
2330   if (OrigTy.getSizeInBits() >= 64)
2331     return N;
2332
2333   // Must extend size to at least 64 bits to be used as an operand for VMULL.
2334   EVT NewVT = getExtensionTo64Bits(OrigTy);
2335
2336   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2337 }
2338
2339 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2340                                    bool isSigned) {
2341   EVT VT = N->getValueType(0);
2342
2343   if (N->getOpcode() != ISD::BUILD_VECTOR)
2344     return false;
2345
2346   for (const SDValue &Elt : N->op_values()) {
2347     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2348       unsigned EltSize = VT.getScalarSizeInBits();
2349       unsigned HalfSize = EltSize / 2;
2350       if (isSigned) {
2351         if (!isIntN(HalfSize, C->getSExtValue()))
2352           return false;
2353       } else {
2354         if (!isUIntN(HalfSize, C->getZExtValue()))
2355           return false;
2356       }
2357       continue;
2358     }
2359     return false;
2360   }
2361
2362   return true;
2363 }
2364
2365 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2366   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2367     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2368                                              N->getOperand(0)->getValueType(0),
2369                                              N->getValueType(0),
2370                                              N->getOpcode());
2371
2372   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2373   EVT VT = N->getValueType(0);
2374   SDLoc dl(N);
2375   unsigned EltSize = VT.getScalarSizeInBits() / 2;
2376   unsigned NumElts = VT.getVectorNumElements();
2377   MVT TruncVT = MVT::getIntegerVT(EltSize);
2378   SmallVector<SDValue, 8> Ops;
2379   for (unsigned i = 0; i != NumElts; ++i) {
2380     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2381     const APInt &CInt = C->getAPIntValue();
2382     // Element types smaller than 32 bits are not legal, so use i32 elements.
2383     // The values are implicitly truncated so sext vs. zext doesn't matter.
2384     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2385   }
2386   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2387 }
2388
2389 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2390   return N->getOpcode() == ISD::SIGN_EXTEND ||
2391          isExtendedBUILD_VECTOR(N, DAG, true);
2392 }
2393
2394 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2395   return N->getOpcode() == ISD::ZERO_EXTEND ||
2396          isExtendedBUILD_VECTOR(N, DAG, false);
2397 }
2398
2399 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2400   unsigned Opcode = N->getOpcode();
2401   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2402     SDNode *N0 = N->getOperand(0).getNode();
2403     SDNode *N1 = N->getOperand(1).getNode();
2404     return N0->hasOneUse() && N1->hasOneUse() &&
2405       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2406   }
2407   return false;
2408 }
2409
2410 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2411   unsigned Opcode = N->getOpcode();
2412   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2413     SDNode *N0 = N->getOperand(0).getNode();
2414     SDNode *N1 = N->getOperand(1).getNode();
2415     return N0->hasOneUse() && N1->hasOneUse() &&
2416       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2417   }
2418   return false;
2419 }
2420
2421 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2422   // Multiplications are only custom-lowered for 128-bit vectors so that
2423   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
2424   EVT VT = Op.getValueType();
2425   assert(VT.is128BitVector() && VT.isInteger() &&
2426          "unexpected type for custom-lowering ISD::MUL");
2427   SDNode *N0 = Op.getOperand(0).getNode();
2428   SDNode *N1 = Op.getOperand(1).getNode();
2429   unsigned NewOpc = 0;
2430   bool isMLA = false;
2431   bool isN0SExt = isSignExtended(N0, DAG);
2432   bool isN1SExt = isSignExtended(N1, DAG);
2433   if (isN0SExt && isN1SExt)
2434     NewOpc = AArch64ISD::SMULL;
2435   else {
2436     bool isN0ZExt = isZeroExtended(N0, DAG);
2437     bool isN1ZExt = isZeroExtended(N1, DAG);
2438     if (isN0ZExt && isN1ZExt)
2439       NewOpc = AArch64ISD::UMULL;
2440     else if (isN1SExt || isN1ZExt) {
2441       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2442       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2443       if (isN1SExt && isAddSubSExt(N0, DAG)) {
2444         NewOpc = AArch64ISD::SMULL;
2445         isMLA = true;
2446       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2447         NewOpc =  AArch64ISD::UMULL;
2448         isMLA = true;
2449       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2450         std::swap(N0, N1);
2451         NewOpc =  AArch64ISD::UMULL;
2452         isMLA = true;
2453       }
2454     }
2455
2456     if (!NewOpc) {
2457       if (VT == MVT::v2i64)
2458         // Fall through to expand this.  It is not legal.
2459         return SDValue();
2460       else
2461         // Other vector multiplications are legal.
2462         return Op;
2463     }
2464   }
2465
2466   // Legalize to a S/UMULL instruction
2467   SDLoc DL(Op);
2468   SDValue Op0;
2469   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2470   if (!isMLA) {
2471     Op0 = skipExtensionForVectorMULL(N0, DAG);
2472     assert(Op0.getValueType().is64BitVector() &&
2473            Op1.getValueType().is64BitVector() &&
2474            "unexpected types for extended operands to VMULL");
2475     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2476   }
2477   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2478   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2479   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2480   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2481   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2482   EVT Op1VT = Op1.getValueType();
2483   return DAG.getNode(N0->getOpcode(), DL, VT,
2484                      DAG.getNode(NewOpc, DL, VT,
2485                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2486                      DAG.getNode(NewOpc, DL, VT,
2487                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2488 }
2489
2490 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2491                                                      SelectionDAG &DAG) const {
2492   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2493   SDLoc dl(Op);
2494   switch (IntNo) {
2495   default: return SDValue();    // Don't custom lower most intrinsics.
2496   case Intrinsic::thread_pointer: {
2497     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2498     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2499   }
2500   case Intrinsic::aarch64_neon_abs:
2501     return DAG.getNode(ISD::ABS, dl, Op.getValueType(),
2502                        Op.getOperand(1));
2503   case Intrinsic::aarch64_neon_smax:
2504     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2505                        Op.getOperand(1), Op.getOperand(2));
2506   case Intrinsic::aarch64_neon_umax:
2507     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2508                        Op.getOperand(1), Op.getOperand(2));
2509   case Intrinsic::aarch64_neon_smin:
2510     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2511                        Op.getOperand(1), Op.getOperand(2));
2512   case Intrinsic::aarch64_neon_umin:
2513     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2514                        Op.getOperand(1), Op.getOperand(2));
2515   }
2516 }
2517
2518 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2519                                               SelectionDAG &DAG) const {
2520   switch (Op.getOpcode()) {
2521   default:
2522     llvm_unreachable("unimplemented operand");
2523     return SDValue();
2524   case ISD::BITCAST:
2525     return LowerBITCAST(Op, DAG);
2526   case ISD::GlobalAddress:
2527     return LowerGlobalAddress(Op, DAG);
2528   case ISD::GlobalTLSAddress:
2529     return LowerGlobalTLSAddress(Op, DAG);
2530   case ISD::SETCC:
2531     return LowerSETCC(Op, DAG);
2532   case ISD::BR_CC:
2533     return LowerBR_CC(Op, DAG);
2534   case ISD::SELECT:
2535     return LowerSELECT(Op, DAG);
2536   case ISD::SELECT_CC:
2537     return LowerSELECT_CC(Op, DAG);
2538   case ISD::JumpTable:
2539     return LowerJumpTable(Op, DAG);
2540   case ISD::ConstantPool:
2541     return LowerConstantPool(Op, DAG);
2542   case ISD::BlockAddress:
2543     return LowerBlockAddress(Op, DAG);
2544   case ISD::VASTART:
2545     return LowerVASTART(Op, DAG);
2546   case ISD::VACOPY:
2547     return LowerVACOPY(Op, DAG);
2548   case ISD::VAARG:
2549     return LowerVAARG(Op, DAG);
2550   case ISD::ADDC:
2551   case ISD::ADDE:
2552   case ISD::SUBC:
2553   case ISD::SUBE:
2554     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2555   case ISD::SADDO:
2556   case ISD::UADDO:
2557   case ISD::SSUBO:
2558   case ISD::USUBO:
2559   case ISD::SMULO:
2560   case ISD::UMULO:
2561     return LowerXALUO(Op, DAG);
2562   case ISD::FADD:
2563     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2564   case ISD::FSUB:
2565     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2566   case ISD::FMUL:
2567     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2568   case ISD::FDIV:
2569     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2570   case ISD::FP_ROUND:
2571     return LowerFP_ROUND(Op, DAG);
2572   case ISD::FP_EXTEND:
2573     return LowerFP_EXTEND(Op, DAG);
2574   case ISD::FRAMEADDR:
2575     return LowerFRAMEADDR(Op, DAG);
2576   case ISD::RETURNADDR:
2577     return LowerRETURNADDR(Op, DAG);
2578   case ISD::INSERT_VECTOR_ELT:
2579     return LowerINSERT_VECTOR_ELT(Op, DAG);
2580   case ISD::EXTRACT_VECTOR_ELT:
2581     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2582   case ISD::BUILD_VECTOR:
2583     return LowerBUILD_VECTOR(Op, DAG);
2584   case ISD::VECTOR_SHUFFLE:
2585     return LowerVECTOR_SHUFFLE(Op, DAG);
2586   case ISD::EXTRACT_SUBVECTOR:
2587     return LowerEXTRACT_SUBVECTOR(Op, DAG);
2588   case ISD::SRA:
2589   case ISD::SRL:
2590   case ISD::SHL:
2591     return LowerVectorSRA_SRL_SHL(Op, DAG);
2592   case ISD::SHL_PARTS:
2593     return LowerShiftLeftParts(Op, DAG);
2594   case ISD::SRL_PARTS:
2595   case ISD::SRA_PARTS:
2596     return LowerShiftRightParts(Op, DAG);
2597   case ISD::CTPOP:
2598     return LowerCTPOP(Op, DAG);
2599   case ISD::FCOPYSIGN:
2600     return LowerFCOPYSIGN(Op, DAG);
2601   case ISD::AND:
2602     return LowerVectorAND(Op, DAG);
2603   case ISD::OR:
2604     return LowerVectorOR(Op, DAG);
2605   case ISD::XOR:
2606     return LowerXOR(Op, DAG);
2607   case ISD::PREFETCH:
2608     return LowerPREFETCH(Op, DAG);
2609   case ISD::SINT_TO_FP:
2610   case ISD::UINT_TO_FP:
2611     return LowerINT_TO_FP(Op, DAG);
2612   case ISD::FP_TO_SINT:
2613   case ISD::FP_TO_UINT:
2614     return LowerFP_TO_INT(Op, DAG);
2615   case ISD::FSINCOS:
2616     return LowerFSINCOS(Op, DAG);
2617   case ISD::MUL:
2618     return LowerMUL(Op, DAG);
2619   case ISD::INTRINSIC_WO_CHAIN:
2620     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2621   case ISD::VECREDUCE_ADD:
2622   case ISD::VECREDUCE_SMAX:
2623   case ISD::VECREDUCE_SMIN:
2624   case ISD::VECREDUCE_UMAX:
2625   case ISD::VECREDUCE_UMIN:
2626   case ISD::VECREDUCE_FMAX:
2627   case ISD::VECREDUCE_FMIN:
2628     return LowerVECREDUCE(Op, DAG);
2629   }
2630 }
2631
2632 //===----------------------------------------------------------------------===//
2633 //                      Calling Convention Implementation
2634 //===----------------------------------------------------------------------===//
2635
2636 #include "AArch64GenCallingConv.inc"
2637
2638 /// Selects the correct CCAssignFn for a given CallingConvention value.
2639 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2640                                                      bool IsVarArg) const {
2641   switch (CC) {
2642   default:
2643     llvm_unreachable("Unsupported calling convention.");
2644   case CallingConv::WebKit_JS:
2645     return CC_AArch64_WebKit_JS;
2646   case CallingConv::GHC:
2647     return CC_AArch64_GHC;
2648   case CallingConv::C:
2649   case CallingConv::Fast:
2650   case CallingConv::PreserveMost:
2651   case CallingConv::CXX_FAST_TLS:
2652   case CallingConv::Swift:
2653     if (!Subtarget->isTargetDarwin())
2654       return CC_AArch64_AAPCS;
2655     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2656   }
2657 }
2658
2659 CCAssignFn *
2660 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2661   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2662                                       : RetCC_AArch64_AAPCS;
2663 }
2664
2665 SDValue AArch64TargetLowering::LowerFormalArguments(
2666     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2667     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2668     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2669   MachineFunction &MF = DAG.getMachineFunction();
2670   MachineFrameInfo &MFI = MF.getFrameInfo();
2671
2672   // Assign locations to all of the incoming arguments.
2673   SmallVector<CCValAssign, 16> ArgLocs;
2674   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2675                  *DAG.getContext());
2676
2677   // At this point, Ins[].VT may already be promoted to i32. To correctly
2678   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2679   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2680   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2681   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2682   // LocVT.
2683   unsigned NumArgs = Ins.size();
2684   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2685   unsigned CurArgIdx = 0;
2686   for (unsigned i = 0; i != NumArgs; ++i) {
2687     MVT ValVT = Ins[i].VT;
2688     if (Ins[i].isOrigArg()) {
2689       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2690       CurArgIdx = Ins[i].getOrigArgIndex();
2691
2692       // Get type of the original argument.
2693       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2694                                   /*AllowUnknown*/ true);
2695       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2696       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2697       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2698         ValVT = MVT::i8;
2699       else if (ActualMVT == MVT::i16)
2700         ValVT = MVT::i16;
2701     }
2702     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2703     bool Res =
2704         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2705     assert(!Res && "Call operand has unhandled type");
2706     (void)Res;
2707   }
2708   assert(ArgLocs.size() == Ins.size());
2709   SmallVector<SDValue, 16> ArgValues;
2710   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2711     CCValAssign &VA = ArgLocs[i];
2712
2713     if (Ins[i].Flags.isByVal()) {
2714       // Byval is used for HFAs in the PCS, but the system should work in a
2715       // non-compliant manner for larger structs.
2716       EVT PtrVT = getPointerTy(DAG.getDataLayout());
2717       int Size = Ins[i].Flags.getByValSize();
2718       unsigned NumRegs = (Size + 7) / 8;
2719
2720       // FIXME: This works on big-endian for composite byvals, which are the common
2721       // case. It should also work for fundamental types too.
2722       unsigned FrameIdx =
2723         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2724       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2725       InVals.push_back(FrameIdxN);
2726
2727       continue;
2728     }
2729
2730     if (VA.isRegLoc()) {
2731       // Arguments stored in registers.
2732       EVT RegVT = VA.getLocVT();
2733
2734       SDValue ArgValue;
2735       const TargetRegisterClass *RC;
2736
2737       if (RegVT == MVT::i32)
2738         RC = &AArch64::GPR32RegClass;
2739       else if (RegVT == MVT::i64)
2740         RC = &AArch64::GPR64RegClass;
2741       else if (RegVT == MVT::f16)
2742         RC = &AArch64::FPR16RegClass;
2743       else if (RegVT == MVT::f32)
2744         RC = &AArch64::FPR32RegClass;
2745       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2746         RC = &AArch64::FPR64RegClass;
2747       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2748         RC = &AArch64::FPR128RegClass;
2749       else
2750         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2751
2752       // Transform the arguments in physical registers into virtual ones.
2753       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2754       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2755
2756       // If this is an 8, 16 or 32-bit value, it is really passed promoted
2757       // to 64 bits.  Insert an assert[sz]ext to capture this, then
2758       // truncate to the right size.
2759       switch (VA.getLocInfo()) {
2760       default:
2761         llvm_unreachable("Unknown loc info!");
2762       case CCValAssign::Full:
2763         break;
2764       case CCValAssign::BCvt:
2765         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2766         break;
2767       case CCValAssign::AExt:
2768       case CCValAssign::SExt:
2769       case CCValAssign::ZExt:
2770         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2771         // nodes after our lowering.
2772         assert(RegVT == Ins[i].VT && "incorrect register location selected");
2773         break;
2774       }
2775
2776       InVals.push_back(ArgValue);
2777
2778     } else { // VA.isRegLoc()
2779       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2780       unsigned ArgOffset = VA.getLocMemOffset();
2781       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2782
2783       uint32_t BEAlign = 0;
2784       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2785           !Ins[i].Flags.isInConsecutiveRegs())
2786         BEAlign = 8 - ArgSize;
2787
2788       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2789
2790       // Create load nodes to retrieve arguments from the stack.
2791       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2792       SDValue ArgValue;
2793
2794       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2795       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2796       MVT MemVT = VA.getValVT();
2797
2798       switch (VA.getLocInfo()) {
2799       default:
2800         break;
2801       case CCValAssign::BCvt:
2802         MemVT = VA.getLocVT();
2803         break;
2804       case CCValAssign::SExt:
2805         ExtType = ISD::SEXTLOAD;
2806         break;
2807       case CCValAssign::ZExt:
2808         ExtType = ISD::ZEXTLOAD;
2809         break;
2810       case CCValAssign::AExt:
2811         ExtType = ISD::EXTLOAD;
2812         break;
2813       }
2814
2815       ArgValue = DAG.getExtLoad(
2816           ExtType, DL, VA.getLocVT(), Chain, FIN,
2817           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2818           MemVT);
2819
2820       InVals.push_back(ArgValue);
2821     }
2822   }
2823
2824   // varargs
2825   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2826   if (isVarArg) {
2827     if (!Subtarget->isTargetDarwin()) {
2828       // The AAPCS variadic function ABI is identical to the non-variadic
2829       // one. As a result there may be more arguments in registers and we should
2830       // save them for future reference.
2831       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2832     }
2833
2834     // This will point to the next argument passed via stack.
2835     unsigned StackOffset = CCInfo.getNextStackOffset();
2836     // We currently pass all varargs at 8-byte alignment.
2837     StackOffset = ((StackOffset + 7) & ~7);
2838     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
2839   }
2840
2841   unsigned StackArgSize = CCInfo.getNextStackOffset();
2842   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2843   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2844     // This is a non-standard ABI so by fiat I say we're allowed to make full
2845     // use of the stack area to be popped, which must be aligned to 16 bytes in
2846     // any case:
2847     StackArgSize = alignTo(StackArgSize, 16);
2848
2849     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2850     // a multiple of 16.
2851     FuncInfo->setArgumentStackToRestore(StackArgSize);
2852
2853     // This realignment carries over to the available bytes below. Our own
2854     // callers will guarantee the space is free by giving an aligned value to
2855     // CALLSEQ_START.
2856   }
2857   // Even if we're not expected to free up the space, it's useful to know how
2858   // much is there while considering tail calls (because we can reuse it).
2859   FuncInfo->setBytesInStackArgArea(StackArgSize);
2860
2861   return Chain;
2862 }
2863
2864 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2865                                                 SelectionDAG &DAG,
2866                                                 const SDLoc &DL,
2867                                                 SDValue &Chain) const {
2868   MachineFunction &MF = DAG.getMachineFunction();
2869   MachineFrameInfo &MFI = MF.getFrameInfo();
2870   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2871   auto PtrVT = getPointerTy(DAG.getDataLayout());
2872
2873   SmallVector<SDValue, 8> MemOps;
2874
2875   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2876                                           AArch64::X3, AArch64::X4, AArch64::X5,
2877                                           AArch64::X6, AArch64::X7 };
2878   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2879   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2880
2881   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2882   int GPRIdx = 0;
2883   if (GPRSaveSize != 0) {
2884     GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
2885
2886     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2887
2888     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2889       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2890       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2891       SDValue Store = DAG.getStore(
2892           Val.getValue(1), DL, Val, FIN,
2893           MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
2894       MemOps.push_back(Store);
2895       FIN =
2896           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2897     }
2898   }
2899   FuncInfo->setVarArgsGPRIndex(GPRIdx);
2900   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2901
2902   if (Subtarget->hasFPARMv8()) {
2903     static const MCPhysReg FPRArgRegs[] = {
2904         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2905         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2906     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2907     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2908
2909     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2910     int FPRIdx = 0;
2911     if (FPRSaveSize != 0) {
2912       FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
2913
2914       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2915
2916       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2917         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2918         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2919
2920         SDValue Store = DAG.getStore(
2921             Val.getValue(1), DL, Val, FIN,
2922             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
2923         MemOps.push_back(Store);
2924         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2925                           DAG.getConstant(16, DL, PtrVT));
2926       }
2927     }
2928     FuncInfo->setVarArgsFPRIndex(FPRIdx);
2929     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2930   }
2931
2932   if (!MemOps.empty()) {
2933     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2934   }
2935 }
2936
2937 /// LowerCallResult - Lower the result values of a call into the
2938 /// appropriate copies out of appropriate physical registers.
2939 SDValue AArch64TargetLowering::LowerCallResult(
2940     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2941     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2942     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2943     SDValue ThisVal) const {
2944   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2945                           ? RetCC_AArch64_WebKit_JS
2946                           : RetCC_AArch64_AAPCS;
2947   // Assign locations to each value returned by this call.
2948   SmallVector<CCValAssign, 16> RVLocs;
2949   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2950                  *DAG.getContext());
2951   CCInfo.AnalyzeCallResult(Ins, RetCC);
2952
2953   // Copy all of the result registers out of their specified physreg.
2954   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2955     CCValAssign VA = RVLocs[i];
2956
2957     // Pass 'this' value directly from the argument to return value, to avoid
2958     // reg unit interference
2959     if (i == 0 && isThisReturn) {
2960       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2961              "unexpected return calling convention register assignment");
2962       InVals.push_back(ThisVal);
2963       continue;
2964     }
2965
2966     SDValue Val =
2967         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2968     Chain = Val.getValue(1);
2969     InFlag = Val.getValue(2);
2970
2971     switch (VA.getLocInfo()) {
2972     default:
2973       llvm_unreachable("Unknown loc info!");
2974     case CCValAssign::Full:
2975       break;
2976     case CCValAssign::BCvt:
2977       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2978       break;
2979     }
2980
2981     InVals.push_back(Val);
2982   }
2983
2984   return Chain;
2985 }
2986
2987 /// Return true if the calling convention is one that we can guarantee TCO for.
2988 static bool canGuaranteeTCO(CallingConv::ID CC) {
2989   return CC == CallingConv::Fast;
2990 }
2991
2992 /// Return true if we might ever do TCO for calls with this calling convention.
2993 static bool mayTailCallThisCC(CallingConv::ID CC) {
2994   switch (CC) {
2995   case CallingConv::C:
2996   case CallingConv::PreserveMost:
2997   case CallingConv::Swift:
2998     return true;
2999   default:
3000     return canGuaranteeTCO(CC);
3001   }
3002 }
3003
3004 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3005     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3006     const SmallVectorImpl<ISD::OutputArg> &Outs,
3007     const SmallVectorImpl<SDValue> &OutVals,
3008     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3009   if (!mayTailCallThisCC(CalleeCC))
3010     return false;
3011
3012   MachineFunction &MF = DAG.getMachineFunction();
3013   const Function *CallerF = MF.getFunction();
3014   CallingConv::ID CallerCC = CallerF->getCallingConv();
3015   bool CCMatch = CallerCC == CalleeCC;
3016
3017   // Byval parameters hand the function a pointer directly into the stack area
3018   // we want to reuse during a tail call. Working around this *is* possible (see
3019   // X86) but less efficient and uglier in LowerCall.
3020   for (Function::const_arg_iterator i = CallerF->arg_begin(),
3021                                     e = CallerF->arg_end();
3022        i != e; ++i)
3023     if (i->hasByValAttr())
3024       return false;
3025
3026   if (getTargetMachine().Options.GuaranteedTailCallOpt)
3027     return canGuaranteeTCO(CalleeCC) && CCMatch;
3028
3029   // Externally-defined functions with weak linkage should not be
3030   // tail-called on AArch64 when the OS does not support dynamic
3031   // pre-emption of symbols, as the AAELF spec requires normal calls
3032   // to undefined weak functions to be replaced with a NOP or jump to the
3033   // next instruction. The behaviour of branch instructions in this
3034   // situation (as used for tail calls) is implementation-defined, so we
3035   // cannot rely on the linker replacing the tail call with a return.
3036   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3037     const GlobalValue *GV = G->getGlobal();
3038     const Triple &TT = getTargetMachine().getTargetTriple();
3039     if (GV->hasExternalWeakLinkage() &&
3040         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3041       return false;
3042   }
3043
3044   // Now we search for cases where we can use a tail call without changing the
3045   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3046   // concept.
3047
3048   // I want anyone implementing a new calling convention to think long and hard
3049   // about this assert.
3050   assert((!isVarArg || CalleeCC == CallingConv::C) &&
3051          "Unexpected variadic calling convention");
3052
3053   LLVMContext &C = *DAG.getContext();
3054   if (isVarArg && !Outs.empty()) {
3055     // At least two cases here: if caller is fastcc then we can't have any
3056     // memory arguments (we'd be expected to clean up the stack afterwards). If
3057     // caller is C then we could potentially use its argument area.
3058
3059     // FIXME: for now we take the most conservative of these in both cases:
3060     // disallow all variadic memory operands.
3061     SmallVector<CCValAssign, 16> ArgLocs;
3062     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3063
3064     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
3065     for (const CCValAssign &ArgLoc : ArgLocs)
3066       if (!ArgLoc.isRegLoc())
3067         return false;
3068   }
3069
3070   // Check that the call results are passed in the same way.
3071   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3072                                   CCAssignFnForCall(CalleeCC, isVarArg),
3073                                   CCAssignFnForCall(CallerCC, isVarArg)))
3074     return false;
3075   // The callee has to preserve all registers the caller needs to preserve.
3076   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3077   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3078   if (!CCMatch) {
3079     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3080     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3081       return false;
3082   }
3083
3084   // Nothing more to check if the callee is taking no arguments
3085   if (Outs.empty())
3086     return true;
3087
3088   SmallVector<CCValAssign, 16> ArgLocs;
3089   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3090
3091   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3092
3093   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3094
3095   // If the stack arguments for this call do not fit into our own save area then
3096   // the call cannot be made tail.
3097   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3098     return false;
3099
3100   const MachineRegisterInfo &MRI = MF.getRegInfo();
3101   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3102     return false;
3103
3104   return true;
3105 }
3106
3107 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3108                                                    SelectionDAG &DAG,
3109                                                    MachineFrameInfo &MFI,
3110                                                    int ClobberedFI) const {
3111   SmallVector<SDValue, 8> ArgChains;
3112   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3113   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
3114
3115   // Include the original chain at the beginning of the list. When this is
3116   // used by target LowerCall hooks, this helps legalize find the
3117   // CALLSEQ_BEGIN node.
3118   ArgChains.push_back(Chain);
3119
3120   // Add a chain value for each stack argument corresponding
3121   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3122                             UE = DAG.getEntryNode().getNode()->use_end();
3123        U != UE; ++U)
3124     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3125       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3126         if (FI->getIndex() < 0) {
3127           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
3128           int64_t InLastByte = InFirstByte;
3129           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
3130
3131           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3132               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3133             ArgChains.push_back(SDValue(L, 1));
3134         }
3135
3136   // Build a tokenfactor for all the chains.
3137   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3138 }
3139
3140 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3141                                                    bool TailCallOpt) const {
3142   return CallCC == CallingConv::Fast && TailCallOpt;
3143 }
3144
3145 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3146 /// and add input and output parameter nodes.
3147 SDValue
3148 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3149                                  SmallVectorImpl<SDValue> &InVals) const {
3150   SelectionDAG &DAG = CLI.DAG;
3151   SDLoc &DL = CLI.DL;
3152   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3153   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3154   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3155   SDValue Chain = CLI.Chain;
3156   SDValue Callee = CLI.Callee;
3157   bool &IsTailCall = CLI.IsTailCall;
3158   CallingConv::ID CallConv = CLI.CallConv;
3159   bool IsVarArg = CLI.IsVarArg;
3160
3161   MachineFunction &MF = DAG.getMachineFunction();
3162   bool IsThisReturn = false;
3163
3164   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3165   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3166   bool IsSibCall = false;
3167
3168   if (IsTailCall) {
3169     // Check if it's really possible to do a tail call.
3170     IsTailCall = isEligibleForTailCallOptimization(
3171         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3172     if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
3173       report_fatal_error("failed to perform tail call elimination on a call "
3174                          "site marked musttail");
3175
3176     // A sibling call is one where we're under the usual C ABI and not planning
3177     // to change that but can still do a tail call:
3178     if (!TailCallOpt && IsTailCall)
3179       IsSibCall = true;
3180
3181     if (IsTailCall)
3182       ++NumTailCalls;
3183   }
3184
3185   // Analyze operands of the call, assigning locations to each operand.
3186   SmallVector<CCValAssign, 16> ArgLocs;
3187   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3188                  *DAG.getContext());
3189
3190   if (IsVarArg) {
3191     // Handle fixed and variable vector arguments differently.
3192     // Variable vector arguments always go into memory.
3193     unsigned NumArgs = Outs.size();
3194
3195     for (unsigned i = 0; i != NumArgs; ++i) {
3196       MVT ArgVT = Outs[i].VT;
3197       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3198       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3199                                                /*IsVarArg=*/ !Outs[i].IsFixed);
3200       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3201       assert(!Res && "Call operand has unhandled type");
3202       (void)Res;
3203     }
3204   } else {
3205     // At this point, Outs[].VT may already be promoted to i32. To correctly
3206     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3207     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3208     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3209     // we use a special version of AnalyzeCallOperands to pass in ValVT and
3210     // LocVT.
3211     unsigned NumArgs = Outs.size();
3212     for (unsigned i = 0; i != NumArgs; ++i) {
3213       MVT ValVT = Outs[i].VT;
3214       // Get type of the original argument.
3215       EVT ActualVT = getValueType(DAG.getDataLayout(),
3216                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3217                                   /*AllowUnknown*/ true);
3218       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3219       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3220       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3221       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3222         ValVT = MVT::i8;
3223       else if (ActualMVT == MVT::i16)
3224         ValVT = MVT::i16;
3225
3226       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3227       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3228       assert(!Res && "Call operand has unhandled type");
3229       (void)Res;
3230     }
3231   }
3232
3233   // Get a count of how many bytes are to be pushed on the stack.
3234   unsigned NumBytes = CCInfo.getNextStackOffset();
3235
3236   if (IsSibCall) {
3237     // Since we're not changing the ABI to make this a tail call, the memory
3238     // operands are already available in the caller's incoming argument space.
3239     NumBytes = 0;
3240   }
3241
3242   // FPDiff is the byte offset of the call's argument area from the callee's.
3243   // Stores to callee stack arguments will be placed in FixedStackSlots offset
3244   // by this amount for a tail call. In a sibling call it must be 0 because the
3245   // caller will deallocate the entire stack and the callee still expects its
3246   // arguments to begin at SP+0. Completely unused for non-tail calls.
3247   int FPDiff = 0;
3248
3249   if (IsTailCall && !IsSibCall) {
3250     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3251
3252     // Since callee will pop argument stack as a tail call, we must keep the
3253     // popped size 16-byte aligned.
3254     NumBytes = alignTo(NumBytes, 16);
3255
3256     // FPDiff will be negative if this tail call requires more space than we
3257     // would automatically have in our incoming argument space. Positive if we
3258     // can actually shrink the stack.
3259     FPDiff = NumReusableBytes - NumBytes;
3260
3261     // The stack pointer must be 16-byte aligned at all times it's used for a
3262     // memory operation, which in practice means at *all* times and in
3263     // particular across call boundaries. Therefore our own arguments started at
3264     // a 16-byte aligned SP and the delta applied for the tail call should
3265     // satisfy the same constraint.
3266     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3267   }
3268
3269   // Adjust the stack pointer for the new arguments...
3270   // These operations are automatically eliminated by the prolog/epilog pass
3271   if (!IsSibCall)
3272     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
3273
3274   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3275                                         getPointerTy(DAG.getDataLayout()));
3276
3277   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3278   SmallVector<SDValue, 8> MemOpChains;
3279   auto PtrVT = getPointerTy(DAG.getDataLayout());
3280
3281   // Walk the register/memloc assignments, inserting copies/loads.
3282   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3283        ++i, ++realArgIdx) {
3284     CCValAssign &VA = ArgLocs[i];
3285     SDValue Arg = OutVals[realArgIdx];
3286     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3287
3288     // Promote the value if needed.
3289     switch (VA.getLocInfo()) {
3290     default:
3291       llvm_unreachable("Unknown loc info!");
3292     case CCValAssign::Full:
3293       break;
3294     case CCValAssign::SExt:
3295       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3296       break;
3297     case CCValAssign::ZExt:
3298       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3299       break;
3300     case CCValAssign::AExt:
3301       if (Outs[realArgIdx].ArgVT == MVT::i1) {
3302         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3303         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3304         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3305       }
3306       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3307       break;
3308     case CCValAssign::BCvt:
3309       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3310       break;
3311     case CCValAssign::FPExt:
3312       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3313       break;
3314     }
3315
3316     if (VA.isRegLoc()) {
3317       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3318           Outs[0].VT == MVT::i64) {
3319         assert(VA.getLocVT() == MVT::i64 &&
3320                "unexpected calling convention register assignment");
3321         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3322                "unexpected use of 'returned'");
3323         IsThisReturn = true;
3324       }
3325       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3326     } else {
3327       assert(VA.isMemLoc());
3328
3329       SDValue DstAddr;
3330       MachinePointerInfo DstInfo;
3331
3332       // FIXME: This works on big-endian for composite byvals, which are the
3333       // common case. It should also work for fundamental types too.
3334       uint32_t BEAlign = 0;
3335       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3336                                         : VA.getValVT().getSizeInBits();
3337       OpSize = (OpSize + 7) / 8;
3338       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3339           !Flags.isInConsecutiveRegs()) {
3340         if (OpSize < 8)
3341           BEAlign = 8 - OpSize;
3342       }
3343       unsigned LocMemOffset = VA.getLocMemOffset();
3344       int32_t Offset = LocMemOffset + BEAlign;
3345       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3346       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3347
3348       if (IsTailCall) {
3349         Offset = Offset + FPDiff;
3350         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3351
3352         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3353         DstInfo =
3354             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3355
3356         // Make sure any stack arguments overlapping with where we're storing
3357         // are loaded before this eventual operation. Otherwise they'll be
3358         // clobbered.
3359         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3360       } else {
3361         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3362
3363         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3364         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3365                                                LocMemOffset);
3366       }
3367
3368       if (Outs[i].Flags.isByVal()) {
3369         SDValue SizeNode =
3370             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3371         SDValue Cpy = DAG.getMemcpy(
3372             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3373             /*isVol = */ false, /*AlwaysInline = */ false,
3374             /*isTailCall = */ false,
3375             DstInfo, MachinePointerInfo());
3376
3377         MemOpChains.push_back(Cpy);
3378       } else {
3379         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3380         // promoted to a legal register type i32, we should truncate Arg back to
3381         // i1/i8/i16.
3382         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3383             VA.getValVT() == MVT::i16)
3384           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3385
3386         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3387         MemOpChains.push_back(Store);
3388       }
3389     }
3390   }
3391
3392   if (!MemOpChains.empty())
3393     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3394
3395   // Build a sequence of copy-to-reg nodes chained together with token chain
3396   // and flag operands which copy the outgoing args into the appropriate regs.
3397   SDValue InFlag;
3398   for (auto &RegToPass : RegsToPass) {
3399     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3400                              RegToPass.second, InFlag);
3401     InFlag = Chain.getValue(1);
3402   }
3403
3404   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3405   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3406   // node so that legalize doesn't hack it.
3407   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3408     auto GV = G->getGlobal();
3409     if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3410         AArch64II::MO_GOT) {
3411       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3412       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3413     } else {
3414       const GlobalValue *GV = G->getGlobal();
3415       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3416     }
3417   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3418     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3419         Subtarget->isTargetMachO()) {
3420       const char *Sym = S->getSymbol();
3421       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3422       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3423     } else {
3424       const char *Sym = S->getSymbol();
3425       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3426     }
3427   }
3428
3429   // We don't usually want to end the call-sequence here because we would tidy
3430   // the frame up *after* the call, however in the ABI-changing tail-call case
3431   // we've carefully laid out the parameters so that when sp is reset they'll be
3432   // in the correct location.
3433   if (IsTailCall && !IsSibCall) {
3434     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3435                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3436     InFlag = Chain.getValue(1);
3437   }
3438
3439   std::vector<SDValue> Ops;
3440   Ops.push_back(Chain);
3441   Ops.push_back(Callee);
3442
3443   if (IsTailCall) {
3444     // Each tail call may have to adjust the stack by a different amount, so
3445     // this information must travel along with the operation for eventual
3446     // consumption by emitEpilogue.
3447     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3448   }
3449
3450   // Add argument registers to the end of the list so that they are known live
3451   // into the call.
3452   for (auto &RegToPass : RegsToPass)
3453     Ops.push_back(DAG.getRegister(RegToPass.first,
3454                                   RegToPass.second.getValueType()));
3455
3456   // Add a register mask operand representing the call-preserved registers.
3457   const uint32_t *Mask;
3458   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3459   if (IsThisReturn) {
3460     // For 'this' returns, use the X0-preserving mask if applicable
3461     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3462     if (!Mask) {
3463       IsThisReturn = false;
3464       Mask = TRI->getCallPreservedMask(MF, CallConv);
3465     }
3466   } else
3467     Mask = TRI->getCallPreservedMask(MF, CallConv);
3468
3469   assert(Mask && "Missing call preserved mask for calling convention");
3470   Ops.push_back(DAG.getRegisterMask(Mask));
3471
3472   if (InFlag.getNode())
3473     Ops.push_back(InFlag);
3474
3475   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3476
3477   // If we're doing a tall call, use a TC_RETURN here rather than an
3478   // actual call instruction.
3479   if (IsTailCall) {
3480     MF.getFrameInfo().setHasTailCall();
3481     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3482   }
3483
3484   // Returns a chain and a flag for retval copy to use.
3485   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3486   InFlag = Chain.getValue(1);
3487
3488   uint64_t CalleePopBytes =
3489       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
3490
3491   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3492                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3493                              InFlag, DL);
3494   if (!Ins.empty())
3495     InFlag = Chain.getValue(1);
3496
3497   // Handle result values, copying them out of physregs into vregs that we
3498   // return.
3499   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3500                          InVals, IsThisReturn,
3501                          IsThisReturn ? OutVals[0] : SDValue());
3502 }
3503
3504 bool AArch64TargetLowering::CanLowerReturn(
3505     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3506     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3507   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3508                           ? RetCC_AArch64_WebKit_JS
3509                           : RetCC_AArch64_AAPCS;
3510   SmallVector<CCValAssign, 16> RVLocs;
3511   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3512   return CCInfo.CheckReturn(Outs, RetCC);
3513 }
3514
3515 SDValue
3516 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3517                                    bool isVarArg,
3518                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3519                                    const SmallVectorImpl<SDValue> &OutVals,
3520                                    const SDLoc &DL, SelectionDAG &DAG) const {
3521   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3522                           ? RetCC_AArch64_WebKit_JS
3523                           : RetCC_AArch64_AAPCS;
3524   SmallVector<CCValAssign, 16> RVLocs;
3525   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3526                  *DAG.getContext());
3527   CCInfo.AnalyzeReturn(Outs, RetCC);
3528
3529   // Copy the result values into the output registers.
3530   SDValue Flag;
3531   SmallVector<SDValue, 4> RetOps(1, Chain);
3532   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3533        ++i, ++realRVLocIdx) {
3534     CCValAssign &VA = RVLocs[i];
3535     assert(VA.isRegLoc() && "Can only return in registers!");
3536     SDValue Arg = OutVals[realRVLocIdx];
3537
3538     switch (VA.getLocInfo()) {
3539     default:
3540       llvm_unreachable("Unknown loc info!");
3541     case CCValAssign::Full:
3542       if (Outs[i].ArgVT == MVT::i1) {
3543         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3544         // value. This is strictly redundant on Darwin (which uses "zeroext
3545         // i1"), but will be optimised out before ISel.
3546         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3547         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3548       }
3549       break;
3550     case CCValAssign::BCvt:
3551       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3552       break;
3553     }
3554
3555     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3556     Flag = Chain.getValue(1);
3557     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3558   }
3559   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3560   const MCPhysReg *I =
3561       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3562   if (I) {
3563     for (; *I; ++I) {
3564       if (AArch64::GPR64RegClass.contains(*I))
3565         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3566       else if (AArch64::FPR64RegClass.contains(*I))
3567         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3568       else
3569         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3570     }
3571   }
3572
3573   RetOps[0] = Chain; // Update chain.
3574
3575   // Add the flag if we have it.
3576   if (Flag.getNode())
3577     RetOps.push_back(Flag);
3578
3579   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3580 }
3581
3582 //===----------------------------------------------------------------------===//
3583 //  Other Lowering Code
3584 //===----------------------------------------------------------------------===//
3585
3586 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
3587                                              SelectionDAG &DAG,
3588                                              unsigned Flag) const {
3589   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
3590 }
3591
3592 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
3593                                              SelectionDAG &DAG,
3594                                              unsigned Flag) const {
3595   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
3596 }
3597
3598 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
3599                                              SelectionDAG &DAG,
3600                                              unsigned Flag) const {
3601   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
3602                                    N->getOffset(), Flag);
3603 }
3604
3605 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
3606                                              SelectionDAG &DAG,
3607                                              unsigned Flag) const {
3608   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
3609 }
3610
3611 // (loadGOT sym)
3612 template <class NodeTy>
3613 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG) const {
3614   DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
3615   SDLoc DL(N);
3616   EVT Ty = getPointerTy(DAG.getDataLayout());
3617   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT);
3618   // FIXME: Once remat is capable of dealing with instructions with register
3619   // operands, expand this into two nodes instead of using a wrapper node.
3620   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
3621 }
3622
3623 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
3624 template <class NodeTy>
3625 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG)
3626   const {
3627   DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
3628   SDLoc DL(N);
3629   EVT Ty = getPointerTy(DAG.getDataLayout());
3630   const unsigned char MO_NC = AArch64II::MO_NC;
3631   return DAG.getNode(
3632         AArch64ISD::WrapperLarge, DL, Ty,
3633         getTargetNode(N, Ty, DAG, AArch64II::MO_G3),
3634         getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC),
3635         getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC),
3636         getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC));
3637 }
3638
3639 // (addlow (adrp %hi(sym)) %lo(sym))
3640 template <class NodeTy>
3641 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG) const {
3642   DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
3643   SDLoc DL(N);
3644   EVT Ty = getPointerTy(DAG.getDataLayout());
3645   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE);
3646   SDValue Lo = getTargetNode(N, Ty, DAG,
3647                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3648   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
3649   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
3650 }
3651
3652 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3653                                                   SelectionDAG &DAG) const {
3654   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3655   const GlobalValue *GV = GN->getGlobal();
3656   unsigned char OpFlags =
3657       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3658
3659   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3660          "unexpected offset in global node");
3661
3662   // This also catches the large code model case for Darwin.
3663   if ((OpFlags & AArch64II::MO_GOT) != 0) {
3664     return getGOT(GN, DAG);
3665   }
3666
3667   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3668     return getAddrLarge(GN, DAG);
3669   } else {
3670     return getAddr(GN, DAG);
3671   }
3672 }
3673
3674 /// \brief Convert a TLS address reference into the correct sequence of loads
3675 /// and calls to compute the variable's address (for Darwin, currently) and
3676 /// return an SDValue containing the final node.
3677
3678 /// Darwin only has one TLS scheme which must be capable of dealing with the
3679 /// fully general situation, in the worst case. This means:
3680 ///     + "extern __thread" declaration.
3681 ///     + Defined in a possibly unknown dynamic library.
3682 ///
3683 /// The general system is that each __thread variable has a [3 x i64] descriptor
3684 /// which contains information used by the runtime to calculate the address. The
3685 /// only part of this the compiler needs to know about is the first xword, which
3686 /// contains a function pointer that must be called with the address of the
3687 /// entire descriptor in "x0".
3688 ///
3689 /// Since this descriptor may be in a different unit, in general even the
3690 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3691 /// is:
3692 ///     adrp x0, _var@TLVPPAGE
3693 ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
3694 ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
3695 ///                                      ; the function pointer
3696 ///     blr x1                           ; Uses descriptor address in x0
3697 ///     ; Address of _var is now in x0.
3698 ///
3699 /// If the address of _var's descriptor *is* known to the linker, then it can
3700 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3701 /// a slight efficiency gain.
3702 SDValue
3703 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3704                                                    SelectionDAG &DAG) const {
3705   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3706
3707   SDLoc DL(Op);
3708   MVT PtrVT = getPointerTy(DAG.getDataLayout());
3709   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3710
3711   SDValue TLVPAddr =
3712       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3713   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3714
3715   // The first entry in the descriptor is a function pointer that we must call
3716   // to obtain the address of the variable.
3717   SDValue Chain = DAG.getEntryNode();
3718   SDValue FuncTLVGet = DAG.getLoad(
3719       MVT::i64, DL, Chain, DescAddr,
3720       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3721       /* Alignment = */ 8,
3722       MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
3723           MachineMemOperand::MODereferenceable);
3724   Chain = FuncTLVGet.getValue(1);
3725
3726   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3727   MFI.setAdjustsStack(true);
3728
3729   // TLS calls preserve all registers except those that absolutely must be
3730   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3731   // silly).
3732   const uint32_t *Mask =
3733       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3734
3735   // Finally, we can make the call. This is just a degenerate version of a
3736   // normal AArch64 call node: x0 takes the address of the descriptor, and
3737   // returns the address of the variable in this thread.
3738   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3739   Chain =
3740       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3741                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3742                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3743   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3744 }
3745
3746 /// When accessing thread-local variables under either the general-dynamic or
3747 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3748 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3749 /// is a function pointer to carry out the resolution.
3750 ///
3751 /// The sequence is:
3752 ///    adrp  x0, :tlsdesc:var
3753 ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
3754 ///    add   x0, x0, #:tlsdesc_lo12:var
3755 ///    .tlsdesccall var
3756 ///    blr   x1
3757 ///    (TPIDR_EL0 offset now in x0)
3758 ///
3759 ///  The above sequence must be produced unscheduled, to enable the linker to
3760 ///  optimize/relax this sequence.
3761 ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3762 ///  above sequence, and expanded really late in the compilation flow, to ensure
3763 ///  the sequence is produced as per above.
3764 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3765                                                       const SDLoc &DL,
3766                                                       SelectionDAG &DAG) const {
3767   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3768
3769   SDValue Chain = DAG.getEntryNode();
3770   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3771
3772   Chain =
3773       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
3774   SDValue Glue = Chain.getValue(1);
3775
3776   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3777 }
3778
3779 SDValue
3780 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3781                                                 SelectionDAG &DAG) const {
3782   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3783   assert(Subtarget->useSmallAddressing() &&
3784          "ELF TLS only supported in small memory model");
3785   // Different choices can be made for the maximum size of the TLS area for a
3786   // module. For the small address model, the default TLS size is 16MiB and the
3787   // maximum TLS size is 4GiB.
3788   // FIXME: add -mtls-size command line option and make it control the 16MiB
3789   // vs. 4GiB code sequence generation.
3790   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3791
3792   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3793
3794   if (DAG.getTarget().Options.EmulatedTLS)
3795     return LowerToTLSEmulatedModel(GA, DAG);
3796
3797   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3798     if (Model == TLSModel::LocalDynamic)
3799       Model = TLSModel::GeneralDynamic;
3800   }
3801
3802   SDValue TPOff;
3803   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3804   SDLoc DL(Op);
3805   const GlobalValue *GV = GA->getGlobal();
3806
3807   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3808
3809   if (Model == TLSModel::LocalExec) {
3810     SDValue HiVar = DAG.getTargetGlobalAddress(
3811         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3812     SDValue LoVar = DAG.getTargetGlobalAddress(
3813         GV, DL, PtrVT, 0,
3814         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3815
3816     SDValue TPWithOff_lo =
3817         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3818                                    HiVar,
3819                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3820                 0);
3821     SDValue TPWithOff =
3822         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3823                                    LoVar,
3824                                    DAG.getTargetConstant(0, DL, MVT::i32)),
3825                 0);
3826     return TPWithOff;
3827   } else if (Model == TLSModel::InitialExec) {
3828     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3829     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3830   } else if (Model == TLSModel::LocalDynamic) {
3831     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3832     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3833     // the beginning of the module's TLS region, followed by a DTPREL offset
3834     // calculation.
3835
3836     // These accesses will need deduplicating if there's more than one.
3837     AArch64FunctionInfo *MFI =
3838         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3839     MFI->incNumLocalDynamicTLSAccesses();
3840
3841     // The call needs a relocation too for linker relaxation. It doesn't make
3842     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3843     // the address.
3844     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3845                                                   AArch64II::MO_TLS);
3846
3847     // Now we can calculate the offset from TPIDR_EL0 to this module's
3848     // thread-local area.
3849     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3850
3851     // Now use :dtprel_whatever: operations to calculate this variable's offset
3852     // in its thread-storage area.
3853     SDValue HiVar = DAG.getTargetGlobalAddress(
3854         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3855     SDValue LoVar = DAG.getTargetGlobalAddress(
3856         GV, DL, MVT::i64, 0,
3857         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3858
3859     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3860                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3861                     0);
3862     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3863                                        DAG.getTargetConstant(0, DL, MVT::i32)),
3864                     0);
3865   } else if (Model == TLSModel::GeneralDynamic) {
3866     // The call needs a relocation too for linker relaxation. It doesn't make
3867     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3868     // the address.
3869     SDValue SymAddr =
3870         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3871
3872     // Finally we can make a call to calculate the offset from tpidr_el0.
3873     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3874   } else
3875     llvm_unreachable("Unsupported ELF TLS access model");
3876
3877   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3878 }
3879
3880 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3881                                                      SelectionDAG &DAG) const {
3882   if (Subtarget->isTargetDarwin())
3883     return LowerDarwinGlobalTLSAddress(Op, DAG);
3884   if (Subtarget->isTargetELF())
3885     return LowerELFGlobalTLSAddress(Op, DAG);
3886
3887   llvm_unreachable("Unexpected platform trying to use TLS");
3888 }
3889
3890 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3891   SDValue Chain = Op.getOperand(0);
3892   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3893   SDValue LHS = Op.getOperand(2);
3894   SDValue RHS = Op.getOperand(3);
3895   SDValue Dest = Op.getOperand(4);
3896   SDLoc dl(Op);
3897
3898   // Handle f128 first, since lowering it will result in comparing the return
3899   // value of a libcall against zero, which is just what the rest of LowerBR_CC
3900   // is expecting to deal with.
3901   if (LHS.getValueType() == MVT::f128) {
3902     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3903
3904     // If softenSetCCOperands returned a scalar, we need to compare the result
3905     // against zero to select between true and false values.
3906     if (!RHS.getNode()) {
3907       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3908       CC = ISD::SETNE;
3909     }
3910   }
3911
3912   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3913   // instruction.
3914   unsigned Opc = LHS.getOpcode();
3915   if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
3916       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3917        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3918     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3919            "Unexpected condition code.");
3920     // Only lower legal XALUO ops.
3921     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3922       return SDValue();
3923
3924     // The actual operation with overflow check.
3925     AArch64CC::CondCode OFCC;
3926     SDValue Value, Overflow;
3927     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3928
3929     if (CC == ISD::SETNE)
3930       OFCC = getInvertedCondCode(OFCC);
3931     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3932
3933     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3934                        Overflow);
3935   }
3936
3937   if (LHS.getValueType().isInteger()) {
3938     assert((LHS.getValueType() == RHS.getValueType()) &&
3939            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3940
3941     // If the RHS of the comparison is zero, we can potentially fold this
3942     // to a specialized branch.
3943     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3944     if (RHSC && RHSC->getZExtValue() == 0) {
3945       if (CC == ISD::SETEQ) {
3946         // See if we can use a TBZ to fold in an AND as well.
3947         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3948         // out of bounds, a late MI-layer pass rewrites branches.
3949         // 403.gcc is an example that hits this case.
3950         if (LHS.getOpcode() == ISD::AND &&
3951             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3952             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3953           SDValue Test = LHS.getOperand(0);
3954           uint64_t Mask = LHS.getConstantOperandVal(1);
3955           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3956                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3957                              Dest);
3958         }
3959
3960         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3961       } else if (CC == ISD::SETNE) {
3962         // See if we can use a TBZ to fold in an AND as well.
3963         // TBZ has a smaller branch displacement than CBZ.  If the offset is
3964         // out of bounds, a late MI-layer pass rewrites branches.
3965         // 403.gcc is an example that hits this case.
3966         if (LHS.getOpcode() == ISD::AND &&
3967             isa<ConstantSDNode>(LHS.getOperand(1)) &&
3968             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3969           SDValue Test = LHS.getOperand(0);
3970           uint64_t Mask = LHS.getConstantOperandVal(1);
3971           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3972                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3973                              Dest);
3974         }
3975
3976         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3977       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3978         // Don't combine AND since emitComparison converts the AND to an ANDS
3979         // (a.k.a. TST) and the test in the test bit and branch instruction
3980         // becomes redundant.  This would also increase register pressure.
3981         uint64_t Mask = LHS.getValueSizeInBits() - 1;
3982         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3983                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
3984       }
3985     }
3986     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3987         LHS.getOpcode() != ISD::AND) {
3988       // Don't combine AND since emitComparison converts the AND to an ANDS
3989       // (a.k.a. TST) and the test in the test bit and branch instruction
3990       // becomes redundant.  This would also increase register pressure.
3991       uint64_t Mask = LHS.getValueSizeInBits() - 1;
3992       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3993                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
3994     }
3995
3996     SDValue CCVal;
3997     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3998     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3999                        Cmp);
4000   }
4001
4002   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4003
4004   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4005   // clean.  Some of them require two branches to implement.
4006   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4007   AArch64CC::CondCode CC1, CC2;
4008   changeFPCCToAArch64CC(CC, CC1, CC2);
4009   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4010   SDValue BR1 =
4011       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4012   if (CC2 != AArch64CC::AL) {
4013     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4014     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4015                        Cmp);
4016   }
4017
4018   return BR1;
4019 }
4020
4021 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4022                                               SelectionDAG &DAG) const {
4023   EVT VT = Op.getValueType();
4024   SDLoc DL(Op);
4025
4026   SDValue In1 = Op.getOperand(0);
4027   SDValue In2 = Op.getOperand(1);
4028   EVT SrcVT = In2.getValueType();
4029
4030   if (SrcVT.bitsLT(VT))
4031     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4032   else if (SrcVT.bitsGT(VT))
4033     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
4034
4035   EVT VecVT;
4036   EVT EltVT;
4037   uint64_t EltMask;
4038   SDValue VecVal1, VecVal2;
4039   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4040     EltVT = MVT::i32;
4041     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4042     EltMask = 0x80000000ULL;
4043
4044     if (!VT.isVector()) {
4045       VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
4046                                           DAG.getUNDEF(VecVT), In1);
4047       VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
4048                                           DAG.getUNDEF(VecVT), In2);
4049     } else {
4050       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4051       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4052     }
4053   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
4054     EltVT = MVT::i64;
4055     VecVT = MVT::v2i64;
4056
4057     // We want to materialize a mask with the high bit set, but the AdvSIMD
4058     // immediate moves cannot materialize that in a single instruction for
4059     // 64-bit elements. Instead, materialize zero and then negate it.
4060     EltMask = 0;
4061
4062     if (!VT.isVector()) {
4063       VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
4064                                           DAG.getUNDEF(VecVT), In1);
4065       VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
4066                                           DAG.getUNDEF(VecVT), In2);
4067     } else {
4068       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4069       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4070     }
4071   } else {
4072     llvm_unreachable("Invalid type for copysign!");
4073   }
4074
4075   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
4076
4077   // If we couldn't materialize the mask above, then the mask vector will be
4078   // the zero vector, and we need to negate it here.
4079   if (VT == MVT::f64 || VT == MVT::v2f64) {
4080     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4081     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4082     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4083   }
4084
4085   SDValue Sel =
4086       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4087
4088   if (VT == MVT::f32)
4089     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4090   else if (VT == MVT::f64)
4091     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4092   else
4093     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4094 }
4095
4096 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
4097   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
4098           Attribute::NoImplicitFloat))
4099     return SDValue();
4100
4101   if (!Subtarget->hasNEON())
4102     return SDValue();
4103
4104   // While there is no integer popcount instruction, it can
4105   // be more efficiently lowered to the following sequence that uses
4106   // AdvSIMD registers/instructions as long as the copies to/from
4107   // the AdvSIMD registers are cheap.
4108   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
4109   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
4110   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
4111   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
4112   SDValue Val = Op.getOperand(0);
4113   SDLoc DL(Op);
4114   EVT VT = Op.getValueType();
4115
4116   if (VT == MVT::i32)
4117     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4118   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
4119
4120   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4121   SDValue UaddLV = DAG.getNode(
4122       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4123       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
4124
4125   if (VT == MVT::i64)
4126     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4127   return UaddLV;
4128 }
4129
4130 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4131
4132   if (Op.getValueType().isVector())
4133     return LowerVSETCC(Op, DAG);
4134
4135   SDValue LHS = Op.getOperand(0);
4136   SDValue RHS = Op.getOperand(1);
4137   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4138   SDLoc dl(Op);
4139
4140   // We chose ZeroOrOneBooleanContents, so use zero and one.
4141   EVT VT = Op.getValueType();
4142   SDValue TVal = DAG.getConstant(1, dl, VT);
4143   SDValue FVal = DAG.getConstant(0, dl, VT);
4144
4145   // Handle f128 first, since one possible outcome is a normal integer
4146   // comparison which gets picked up by the next if statement.
4147   if (LHS.getValueType() == MVT::f128) {
4148     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4149
4150     // If softenSetCCOperands returned a scalar, use it.
4151     if (!RHS.getNode()) {
4152       assert(LHS.getValueType() == Op.getValueType() &&
4153              "Unexpected setcc expansion!");
4154       return LHS;
4155     }
4156   }
4157
4158   if (LHS.getValueType().isInteger()) {
4159     SDValue CCVal;
4160     SDValue Cmp =
4161         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
4162
4163     // Note that we inverted the condition above, so we reverse the order of
4164     // the true and false operands here.  This will allow the setcc to be
4165     // matched to a single CSINC instruction.
4166     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4167   }
4168
4169   // Now we know we're dealing with FP values.
4170   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4171
4172   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
4173   // and do the comparison.
4174   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4175
4176   AArch64CC::CondCode CC1, CC2;
4177   changeFPCCToAArch64CC(CC, CC1, CC2);
4178   if (CC2 == AArch64CC::AL) {
4179     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
4180     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4181
4182     // Note that we inverted the condition above, so we reverse the order of
4183     // the true and false operands here.  This will allow the setcc to be
4184     // matched to a single CSINC instruction.
4185     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4186   } else {
4187     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4188     // totally clean.  Some of them require two CSELs to implement.  As is in
4189     // this case, we emit the first CSEL and then emit a second using the output
4190     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
4191
4192     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
4193     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4194     SDValue CS1 =
4195         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4196
4197     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4198     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4199   }
4200 }
4201
4202 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4203                                               SDValue RHS, SDValue TVal,
4204                                               SDValue FVal, const SDLoc &dl,
4205                                               SelectionDAG &DAG) const {
4206   // Handle f128 first, because it will result in a comparison of some RTLIB
4207   // call result against zero.
4208   if (LHS.getValueType() == MVT::f128) {
4209     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4210
4211     // If softenSetCCOperands returned a scalar, we need to compare the result
4212     // against zero to select between true and false values.
4213     if (!RHS.getNode()) {
4214       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4215       CC = ISD::SETNE;
4216     }
4217   }
4218
4219   // Also handle f16, for which we need to do a f32 comparison.
4220   if (LHS.getValueType() == MVT::f16) {
4221     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4222     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4223   }
4224
4225   // Next, handle integers.
4226   if (LHS.getValueType().isInteger()) {
4227     assert((LHS.getValueType() == RHS.getValueType()) &&
4228            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4229
4230     unsigned Opcode = AArch64ISD::CSEL;
4231
4232     // If both the TVal and the FVal are constants, see if we can swap them in
4233     // order to for a CSINV or CSINC out of them.
4234     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4235     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4236
4237     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4238       std::swap(TVal, FVal);
4239       std::swap(CTVal, CFVal);
4240       CC = ISD::getSetCCInverse(CC, true);
4241     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4242       std::swap(TVal, FVal);
4243       std::swap(CTVal, CFVal);
4244       CC = ISD::getSetCCInverse(CC, true);
4245     } else if (TVal.getOpcode() == ISD::XOR) {
4246       // If TVal is a NOT we want to swap TVal and FVal so that we can match
4247       // with a CSINV rather than a CSEL.
4248       if (isAllOnesConstant(TVal.getOperand(1))) {
4249         std::swap(TVal, FVal);
4250         std::swap(CTVal, CFVal);
4251         CC = ISD::getSetCCInverse(CC, true);
4252       }
4253     } else if (TVal.getOpcode() == ISD::SUB) {
4254       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4255       // that we can match with a CSNEG rather than a CSEL.
4256       if (isNullConstant(TVal.getOperand(0))) {
4257         std::swap(TVal, FVal);
4258         std::swap(CTVal, CFVal);
4259         CC = ISD::getSetCCInverse(CC, true);
4260       }
4261     } else if (CTVal && CFVal) {
4262       const int64_t TrueVal = CTVal->getSExtValue();
4263       const int64_t FalseVal = CFVal->getSExtValue();
4264       bool Swap = false;
4265
4266       // If both TVal and FVal are constants, see if FVal is the
4267       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4268       // instead of a CSEL in that case.
4269       if (TrueVal == ~FalseVal) {
4270         Opcode = AArch64ISD::CSINV;
4271       } else if (TrueVal == -FalseVal) {
4272         Opcode = AArch64ISD::CSNEG;
4273       } else if (TVal.getValueType() == MVT::i32) {
4274         // If our operands are only 32-bit wide, make sure we use 32-bit
4275         // arithmetic for the check whether we can use CSINC. This ensures that
4276         // the addition in the check will wrap around properly in case there is
4277         // an overflow (which would not be the case if we do the check with
4278         // 64-bit arithmetic).
4279         const uint32_t TrueVal32 = CTVal->getZExtValue();
4280         const uint32_t FalseVal32 = CFVal->getZExtValue();
4281
4282         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4283           Opcode = AArch64ISD::CSINC;
4284
4285           if (TrueVal32 > FalseVal32) {
4286             Swap = true;
4287           }
4288         }
4289         // 64-bit check whether we can use CSINC.
4290       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4291         Opcode = AArch64ISD::CSINC;
4292
4293         if (TrueVal > FalseVal) {
4294           Swap = true;
4295         }
4296       }
4297
4298       // Swap TVal and FVal if necessary.
4299       if (Swap) {
4300         std::swap(TVal, FVal);
4301         std::swap(CTVal, CFVal);
4302         CC = ISD::getSetCCInverse(CC, true);
4303       }
4304
4305       if (Opcode != AArch64ISD::CSEL) {
4306         // Drop FVal since we can get its value by simply inverting/negating
4307         // TVal.
4308         FVal = TVal;
4309       }
4310     }
4311
4312     // Avoid materializing a constant when possible by reusing a known value in
4313     // a register.  However, don't perform this optimization if the known value
4314     // is one, zero or negative one in the case of a CSEL.  We can always
4315     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4316     // FVal, respectively.
4317     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4318     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4319         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4320       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4321       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4322       // "a != C ? x : a" to avoid materializing C.
4323       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4324         TVal = LHS;
4325       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4326         FVal = LHS;
4327     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4328       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4329       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4330       // avoid materializing C.
4331       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4332       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4333         Opcode = AArch64ISD::CSINV;
4334         TVal = LHS;
4335         FVal = DAG.getConstant(0, dl, FVal.getValueType());
4336       }
4337     }
4338
4339     SDValue CCVal;
4340     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4341
4342     EVT VT = TVal.getValueType();
4343     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4344   }
4345
4346   // Now we know we're dealing with FP values.
4347   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4348   assert(LHS.getValueType() == RHS.getValueType());
4349   EVT VT = TVal.getValueType();
4350   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4351
4352   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4353   // clean.  Some of them require two CSELs to implement.
4354   AArch64CC::CondCode CC1, CC2;
4355   changeFPCCToAArch64CC(CC, CC1, CC2);
4356
4357   if (DAG.getTarget().Options.UnsafeFPMath) {
4358     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4359     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4360     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4361     if (RHSVal && RHSVal->isZero()) {
4362       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4363       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4364
4365       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
4366           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
4367         TVal = LHS;
4368       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
4369                CFVal && CFVal->isZero() &&
4370                FVal.getValueType() == LHS.getValueType())
4371         FVal = LHS;
4372     }
4373   }
4374
4375   // Emit first, and possibly only, CSEL.
4376   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4377   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4378
4379   // If we need a second CSEL, emit it, using the output of the first as the
4380   // RHS.  We're effectively OR'ing the two CC's together.
4381   if (CC2 != AArch64CC::AL) {
4382     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4383     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4384   }
4385
4386   // Otherwise, return the output of the first CSEL.
4387   return CS1;
4388 }
4389
4390 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4391                                               SelectionDAG &DAG) const {
4392   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4393   SDValue LHS = Op.getOperand(0);
4394   SDValue RHS = Op.getOperand(1);
4395   SDValue TVal = Op.getOperand(2);
4396   SDValue FVal = Op.getOperand(3);
4397   SDLoc DL(Op);
4398   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4399 }
4400
4401 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4402                                            SelectionDAG &DAG) const {
4403   SDValue CCVal = Op->getOperand(0);
4404   SDValue TVal = Op->getOperand(1);
4405   SDValue FVal = Op->getOperand(2);
4406   SDLoc DL(Op);
4407
4408   unsigned Opc = CCVal.getOpcode();
4409   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4410   // instruction.
4411   if (CCVal.getResNo() == 1 &&
4412       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4413        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4414     // Only lower legal XALUO ops.
4415     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4416       return SDValue();
4417
4418     AArch64CC::CondCode OFCC;
4419     SDValue Value, Overflow;
4420     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4421     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4422
4423     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4424                        CCVal, Overflow);
4425   }
4426
4427   // Lower it the same way as we would lower a SELECT_CC node.
4428   ISD::CondCode CC;
4429   SDValue LHS, RHS;
4430   if (CCVal.getOpcode() == ISD::SETCC) {
4431     LHS = CCVal.getOperand(0);
4432     RHS = CCVal.getOperand(1);
4433     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4434   } else {
4435     LHS = CCVal;
4436     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4437     CC = ISD::SETNE;
4438   }
4439   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4440 }
4441
4442 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4443                                               SelectionDAG &DAG) const {
4444   // Jump table entries as PC relative offsets. No additional tweaking
4445   // is necessary here. Just get the address of the jump table.
4446   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4447
4448   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4449       !Subtarget->isTargetMachO()) {
4450     return getAddrLarge(JT, DAG);
4451   }
4452   return getAddr(JT, DAG);
4453 }
4454
4455 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4456                                                  SelectionDAG &DAG) const {
4457   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4458
4459   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4460     // Use the GOT for the large code model on iOS.
4461     if (Subtarget->isTargetMachO()) {
4462       return getGOT(CP, DAG);
4463     }
4464     return getAddrLarge(CP, DAG);
4465   } else {
4466     return getAddr(CP, DAG);
4467   }
4468 }
4469
4470 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4471                                                SelectionDAG &DAG) const {
4472   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
4473   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4474       !Subtarget->isTargetMachO()) {
4475     return getAddrLarge(BA, DAG);
4476   } else {
4477     return getAddr(BA, DAG);
4478   }
4479 }
4480
4481 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4482                                                  SelectionDAG &DAG) const {
4483   AArch64FunctionInfo *FuncInfo =
4484       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4485
4486   SDLoc DL(Op);
4487   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4488                                  getPointerTy(DAG.getDataLayout()));
4489   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4490   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4491                       MachinePointerInfo(SV));
4492 }
4493
4494 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4495                                                 SelectionDAG &DAG) const {
4496   // The layout of the va_list struct is specified in the AArch64 Procedure Call
4497   // Standard, section B.3.
4498   MachineFunction &MF = DAG.getMachineFunction();
4499   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4500   auto PtrVT = getPointerTy(DAG.getDataLayout());
4501   SDLoc DL(Op);
4502
4503   SDValue Chain = Op.getOperand(0);
4504   SDValue VAList = Op.getOperand(1);
4505   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4506   SmallVector<SDValue, 4> MemOps;
4507
4508   // void *__stack at offset 0
4509   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4510   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4511                                 MachinePointerInfo(SV), /* Alignment = */ 8));
4512
4513   // void *__gr_top at offset 8
4514   int GPRSize = FuncInfo->getVarArgsGPRSize();
4515   if (GPRSize > 0) {
4516     SDValue GRTop, GRTopAddr;
4517
4518     GRTopAddr =
4519         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4520
4521     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4522     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4523                         DAG.getConstant(GPRSize, DL, PtrVT));
4524
4525     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4526                                   MachinePointerInfo(SV, 8),
4527                                   /* Alignment = */ 8));
4528   }
4529
4530   // void *__vr_top at offset 16
4531   int FPRSize = FuncInfo->getVarArgsFPRSize();
4532   if (FPRSize > 0) {
4533     SDValue VRTop, VRTopAddr;
4534     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4535                             DAG.getConstant(16, DL, PtrVT));
4536
4537     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4538     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4539                         DAG.getConstant(FPRSize, DL, PtrVT));
4540
4541     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4542                                   MachinePointerInfo(SV, 16),
4543                                   /* Alignment = */ 8));
4544   }
4545
4546   // int __gr_offs at offset 24
4547   SDValue GROffsAddr =
4548       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4549   MemOps.push_back(DAG.getStore(
4550       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4551       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
4552
4553   // int __vr_offs at offset 28
4554   SDValue VROffsAddr =
4555       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4556   MemOps.push_back(DAG.getStore(
4557       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4558       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
4559
4560   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4561 }
4562
4563 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4564                                             SelectionDAG &DAG) const {
4565   return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4566                                      : LowerAAPCS_VASTART(Op, DAG);
4567 }
4568
4569 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4570                                            SelectionDAG &DAG) const {
4571   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4572   // pointer.
4573   SDLoc DL(Op);
4574   unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4575   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4576   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4577
4578   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4579                        Op.getOperand(2),
4580                        DAG.getConstant(VaListSize, DL, MVT::i32),
4581                        8, false, false, false, MachinePointerInfo(DestSV),
4582                        MachinePointerInfo(SrcSV));
4583 }
4584
4585 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4586   assert(Subtarget->isTargetDarwin() &&
4587          "automatic va_arg instruction only works on Darwin");
4588
4589   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4590   EVT VT = Op.getValueType();
4591   SDLoc DL(Op);
4592   SDValue Chain = Op.getOperand(0);
4593   SDValue Addr = Op.getOperand(1);
4594   unsigned Align = Op.getConstantOperandVal(3);
4595   auto PtrVT = getPointerTy(DAG.getDataLayout());
4596
4597   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
4598   Chain = VAList.getValue(1);
4599
4600   if (Align > 8) {
4601     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4602     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4603                          DAG.getConstant(Align - 1, DL, PtrVT));
4604     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4605                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4606   }
4607
4608   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4609   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4610
4611   // Scalar integer and FP values smaller than 64 bits are implicitly extended
4612   // up to 64 bits.  At the very least, we have to increase the striding of the
4613   // vaargs list to match this, and for FP values we need to introduce
4614   // FP_ROUND nodes as well.
4615   if (VT.isInteger() && !VT.isVector())
4616     ArgSize = 8;
4617   bool NeedFPTrunc = false;
4618   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4619     ArgSize = 8;
4620     NeedFPTrunc = true;
4621   }
4622
4623   // Increment the pointer, VAList, to the next vaarg
4624   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4625                                DAG.getConstant(ArgSize, DL, PtrVT));
4626   // Store the incremented VAList to the legalized pointer
4627   SDValue APStore =
4628       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
4629
4630   // Load the actual argument out of the pointer VAList
4631   if (NeedFPTrunc) {
4632     // Load the value as an f64.
4633     SDValue WideFP =
4634         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
4635     // Round the value down to an f32.
4636     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4637                                    DAG.getIntPtrConstant(1, DL));
4638     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4639     // Merge the rounded value with the chain output of the load.
4640     return DAG.getMergeValues(Ops, DL);
4641   }
4642
4643   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
4644 }
4645
4646 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4647                                               SelectionDAG &DAG) const {
4648   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4649   MFI.setFrameAddressIsTaken(true);
4650
4651   EVT VT = Op.getValueType();
4652   SDLoc DL(Op);
4653   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4654   SDValue FrameAddr =
4655       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4656   while (Depth--)
4657     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4658                             MachinePointerInfo());
4659   return FrameAddr;
4660 }
4661
4662 // FIXME? Maybe this could be a TableGen attribute on some registers and
4663 // this table could be generated automatically from RegInfo.
4664 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4665                                                   SelectionDAG &DAG) const {
4666   unsigned Reg = StringSwitch<unsigned>(RegName)
4667                        .Case("sp", AArch64::SP)
4668                        .Case("x18", AArch64::X18)
4669                        .Case("w18", AArch64::W18)
4670                        .Default(0);
4671   if ((Reg == AArch64::X18 || Reg == AArch64::W18) &&
4672       !Subtarget->isX18Reserved())
4673     Reg = 0;
4674   if (Reg)
4675     return Reg;
4676   report_fatal_error(Twine("Invalid register name \""
4677                               + StringRef(RegName)  + "\"."));
4678 }
4679
4680 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4681                                                SelectionDAG &DAG) const {
4682   MachineFunction &MF = DAG.getMachineFunction();
4683   MachineFrameInfo &MFI = MF.getFrameInfo();
4684   MFI.setReturnAddressIsTaken(true);
4685
4686   EVT VT = Op.getValueType();
4687   SDLoc DL(Op);
4688   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4689   if (Depth) {
4690     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4691     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4692     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4693                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4694                        MachinePointerInfo());
4695   }
4696
4697   // Return LR, which contains the return address. Mark it an implicit live-in.
4698   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4699   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4700 }
4701
4702 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4703 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4704 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4705                                                     SelectionDAG &DAG) const {
4706   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4707   EVT VT = Op.getValueType();
4708   unsigned VTBits = VT.getSizeInBits();
4709   SDLoc dl(Op);
4710   SDValue ShOpLo = Op.getOperand(0);
4711   SDValue ShOpHi = Op.getOperand(1);
4712   SDValue ShAmt = Op.getOperand(2);
4713   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4714
4715   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4716
4717   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4718                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4719   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4720
4721   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4722   // is "undef". We wanted 0, so CSEL it directly.
4723   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4724                                ISD::SETEQ, dl, DAG);
4725   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4726   HiBitsForLo =
4727       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4728                   HiBitsForLo, CCVal, Cmp);
4729
4730   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4731                                    DAG.getConstant(VTBits, dl, MVT::i64));
4732
4733   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4734   SDValue LoForNormalShift =
4735       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
4736
4737   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4738                        dl, DAG);
4739   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4740   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4741   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4742                            LoForNormalShift, CCVal, Cmp);
4743
4744   // AArch64 shifts larger than the register width are wrapped rather than
4745   // clamped, so we can't just emit "hi >> x".
4746   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4747   SDValue HiForBigShift =
4748       Opc == ISD::SRA
4749           ? DAG.getNode(Opc, dl, VT, ShOpHi,
4750                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
4751           : DAG.getConstant(0, dl, VT);
4752   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4753                            HiForNormalShift, CCVal, Cmp);
4754
4755   SDValue Ops[2] = { Lo, Hi };
4756   return DAG.getMergeValues(Ops, dl);
4757 }
4758
4759 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4760 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4761 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4762                                                    SelectionDAG &DAG) const {
4763   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4764   EVT VT = Op.getValueType();
4765   unsigned VTBits = VT.getSizeInBits();
4766   SDLoc dl(Op);
4767   SDValue ShOpLo = Op.getOperand(0);
4768   SDValue ShOpHi = Op.getOperand(1);
4769   SDValue ShAmt = Op.getOperand(2);
4770
4771   assert(Op.getOpcode() == ISD::SHL_PARTS);
4772   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4773                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4774   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4775
4776   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4777   // is "undef". We wanted 0, so CSEL it directly.
4778   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4779                                ISD::SETEQ, dl, DAG);
4780   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4781   LoBitsForHi =
4782       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4783                   LoBitsForHi, CCVal, Cmp);
4784
4785   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4786                                    DAG.getConstant(VTBits, dl, MVT::i64));
4787   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4788   SDValue HiForNormalShift =
4789       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
4790
4791   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4792
4793   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4794                        dl, DAG);
4795   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4796   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4797                            HiForNormalShift, CCVal, Cmp);
4798
4799   // AArch64 shifts of larger than register sizes are wrapped rather than
4800   // clamped, so we can't just emit "lo << a" if a is too big.
4801   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4802   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4803   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4804                            LoForNormalShift, CCVal, Cmp);
4805
4806   SDValue Ops[2] = { Lo, Hi };
4807   return DAG.getMergeValues(Ops, dl);
4808 }
4809
4810 bool AArch64TargetLowering::isOffsetFoldingLegal(
4811     const GlobalAddressSDNode *GA) const {
4812   // The AArch64 target doesn't support folding offsets into global addresses.
4813   return false;
4814 }
4815
4816 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4817   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4818   // FIXME: We should be able to handle f128 as well with a clever lowering.
4819   if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4820     return true;
4821
4822   if (VT == MVT::f64)
4823     return AArch64_AM::getFP64Imm(Imm) != -1;
4824   else if (VT == MVT::f32)
4825     return AArch64_AM::getFP32Imm(Imm) != -1;
4826   return false;
4827 }
4828
4829 //===----------------------------------------------------------------------===//
4830 //                          AArch64 Optimization Hooks
4831 //===----------------------------------------------------------------------===//
4832
4833 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
4834                            SDValue Operand, SelectionDAG &DAG,
4835                            int &ExtraSteps) {
4836   EVT VT = Operand.getValueType();
4837   if (ST->hasNEON() &&
4838       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
4839        VT == MVT::f32 || VT == MVT::v1f32 ||
4840        VT == MVT::v2f32 || VT == MVT::v4f32)) {
4841     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
4842       // For the reciprocal estimates, convergence is quadratic, so the number
4843       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
4844       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
4845       // the result for float (23 mantissa bits) is 2 and for double (52
4846       // mantissa bits) is 3.
4847       ExtraSteps = VT == MVT::f64 ? 3 : 2;
4848
4849     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4850   }
4851
4852   return SDValue();
4853 }
4854
4855 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
4856                                                SelectionDAG &DAG, int Enabled,
4857                                                int &ExtraSteps,
4858                                                bool &UseOneConst,
4859                                                bool Reciprocal) const {
4860   if (Enabled == ReciprocalEstimate::Enabled ||
4861       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
4862     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
4863                                        DAG, ExtraSteps)) {
4864       SDLoc DL(Operand);
4865       EVT VT = Operand.getValueType();
4866
4867       SDNodeFlags Flags;
4868       Flags.setUnsafeAlgebra(true);
4869
4870       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
4871       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
4872       for (int i = ExtraSteps; i > 0; --i) {
4873         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
4874                                    Flags);
4875         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
4876         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
4877       }
4878
4879       if (!Reciprocal) {
4880         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
4881                                       VT);
4882         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
4883         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
4884
4885         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
4886         // Correct the result if the operand is 0.0.
4887         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
4888                                VT, Eq, Operand, Estimate);
4889       }
4890
4891       ExtraSteps = 0;
4892       return Estimate;
4893     }
4894
4895   return SDValue();
4896 }
4897
4898 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
4899                                                 SelectionDAG &DAG, int Enabled,
4900                                                 int &ExtraSteps) const {
4901   if (Enabled == ReciprocalEstimate::Enabled)
4902     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
4903                                        DAG, ExtraSteps)) {
4904       SDLoc DL(Operand);
4905       EVT VT = Operand.getValueType();
4906
4907       SDNodeFlags Flags;
4908       Flags.setUnsafeAlgebra(true);
4909
4910       // Newton reciprocal iteration: E * (2 - X * E)
4911       // AArch64 reciprocal iteration instruction: (2 - M * N)
4912       for (int i = ExtraSteps; i > 0; --i) {
4913         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
4914                                    Estimate, Flags);
4915         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
4916       }
4917
4918       ExtraSteps = 0;
4919       return Estimate;
4920     }
4921
4922   return SDValue();
4923 }
4924
4925 //===----------------------------------------------------------------------===//
4926 //                          AArch64 Inline Assembly Support
4927 //===----------------------------------------------------------------------===//
4928
4929 // Table of Constraints
4930 // TODO: This is the current set of constraints supported by ARM for the
4931 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4932 //
4933 // r - A general register
4934 // w - An FP/SIMD register of some size in the range v0-v31
4935 // x - An FP/SIMD register of some size in the range v0-v15
4936 // I - Constant that can be used with an ADD instruction
4937 // J - Constant that can be used with a SUB instruction
4938 // K - Constant that can be used with a 32-bit logical instruction
4939 // L - Constant that can be used with a 64-bit logical instruction
4940 // M - Constant that can be used as a 32-bit MOV immediate
4941 // N - Constant that can be used as a 64-bit MOV immediate
4942 // Q - A memory reference with base register and no offset
4943 // S - A symbolic address
4944 // Y - Floating point constant zero
4945 // Z - Integer constant zero
4946 //
4947 //   Note that general register operands will be output using their 64-bit x
4948 // register name, whatever the size of the variable, unless the asm operand
4949 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4950 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4951 // %q modifier.
4952 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4953   // At this point, we have to lower this constraint to something else, so we
4954   // lower it to an "r" or "w". However, by doing this we will force the result
4955   // to be in register, while the X constraint is much more permissive.
4956   //
4957   // Although we are correct (we are free to emit anything, without
4958   // constraints), we might break use cases that would expect us to be more
4959   // efficient and emit something else.
4960   if (!Subtarget->hasFPARMv8())
4961     return "r";
4962
4963   if (ConstraintVT.isFloatingPoint())
4964     return "w";
4965
4966   if (ConstraintVT.isVector() &&
4967      (ConstraintVT.getSizeInBits() == 64 ||
4968       ConstraintVT.getSizeInBits() == 128))
4969     return "w";
4970
4971   return "r";
4972 }
4973
4974 /// getConstraintType - Given a constraint letter, return the type of
4975 /// constraint it is for this target.
4976 AArch64TargetLowering::ConstraintType
4977 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4978   if (Constraint.size() == 1) {
4979     switch (Constraint[0]) {
4980     default:
4981       break;
4982     case 'z':
4983       return C_Other;
4984     case 'x':
4985     case 'w':
4986       return C_RegisterClass;
4987     // An address with a single base register. Due to the way we
4988     // currently handle addresses it is the same as 'r'.
4989     case 'Q':
4990       return C_Memory;
4991     }
4992   }
4993   return TargetLowering::getConstraintType(Constraint);
4994 }
4995
4996 /// Examine constraint type and operand type and determine a weight value.
4997 /// This object must already have been set up with the operand type
4998 /// and the current alternative constraint selected.
4999 TargetLowering::ConstraintWeight
5000 AArch64TargetLowering::getSingleConstraintMatchWeight(
5001     AsmOperandInfo &info, const char *constraint) const {
5002   ConstraintWeight weight = CW_Invalid;
5003   Value *CallOperandVal = info.CallOperandVal;
5004   // If we don't have a value, we can't do a match,
5005   // but allow it at the lowest weight.
5006   if (!CallOperandVal)
5007     return CW_Default;
5008   Type *type = CallOperandVal->getType();
5009   // Look at the constraint type.
5010   switch (*constraint) {
5011   default:
5012     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5013     break;
5014   case 'x':
5015   case 'w':
5016     if (type->isFloatingPointTy() || type->isVectorTy())
5017       weight = CW_Register;
5018     break;
5019   case 'z':
5020     weight = CW_Constant;
5021     break;
5022   }
5023   return weight;
5024 }
5025
5026 std::pair<unsigned, const TargetRegisterClass *>
5027 AArch64TargetLowering::getRegForInlineAsmConstraint(
5028     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
5029   if (Constraint.size() == 1) {
5030     switch (Constraint[0]) {
5031     case 'r':
5032       if (VT.getSizeInBits() == 64)
5033         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5034       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5035     case 'w':
5036       if (VT.getSizeInBits() == 16)
5037         return std::make_pair(0U, &AArch64::FPR16RegClass);
5038       if (VT.getSizeInBits() == 32)
5039         return std::make_pair(0U, &AArch64::FPR32RegClass);
5040       if (VT.getSizeInBits() == 64)
5041         return std::make_pair(0U, &AArch64::FPR64RegClass);
5042       if (VT.getSizeInBits() == 128)
5043         return std::make_pair(0U, &AArch64::FPR128RegClass);
5044       break;
5045     // The instructions that this constraint is designed for can
5046     // only take 128-bit registers so just use that regclass.
5047     case 'x':
5048       if (VT.getSizeInBits() == 128)
5049         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5050       break;
5051     }
5052   }
5053   if (StringRef("{cc}").equals_lower(Constraint))
5054     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5055
5056   // Use the default implementation in TargetLowering to convert the register
5057   // constraint into a member of a register class.
5058   std::pair<unsigned, const TargetRegisterClass *> Res;
5059   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5060
5061   // Not found as a standard register?
5062   if (!Res.second) {
5063     unsigned Size = Constraint.size();
5064     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5065         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
5066       int RegNo;
5067       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5068       if (!Failed && RegNo >= 0 && RegNo <= 31) {
5069         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
5070         // By default we'll emit v0-v31 for this unless there's a modifier where
5071         // we'll emit the correct register as well.
5072         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5073           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5074           Res.second = &AArch64::FPR64RegClass;
5075         } else {
5076           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5077           Res.second = &AArch64::FPR128RegClass;
5078         }
5079       }
5080     }
5081   }
5082
5083   return Res;
5084 }
5085
5086 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5087 /// vector.  If it is invalid, don't add anything to Ops.
5088 void AArch64TargetLowering::LowerAsmOperandForConstraint(
5089     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5090     SelectionDAG &DAG) const {
5091   SDValue Result;
5092
5093   // Currently only support length 1 constraints.
5094   if (Constraint.length() != 1)
5095     return;
5096
5097   char ConstraintLetter = Constraint[0];
5098   switch (ConstraintLetter) {
5099   default:
5100     break;
5101
5102   // This set of constraints deal with valid constants for various instructions.
5103   // Validate and return a target constant for them if we can.
5104   case 'z': {
5105     // 'z' maps to xzr or wzr so it needs an input of 0.
5106     if (!isNullConstant(Op))
5107       return;
5108
5109     if (Op.getValueType() == MVT::i64)
5110       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5111     else
5112       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5113     break;
5114   }
5115
5116   case 'I':
5117   case 'J':
5118   case 'K':
5119   case 'L':
5120   case 'M':
5121   case 'N':
5122     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5123     if (!C)
5124       return;
5125
5126     // Grab the value and do some validation.
5127     uint64_t CVal = C->getZExtValue();
5128     switch (ConstraintLetter) {
5129     // The I constraint applies only to simple ADD or SUB immediate operands:
5130     // i.e. 0 to 4095 with optional shift by 12
5131     // The J constraint applies only to ADD or SUB immediates that would be
5132     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5133     // instruction [or vice versa], in other words -1 to -4095 with optional
5134     // left shift by 12.
5135     case 'I':
5136       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5137         break;
5138       return;
5139     case 'J': {
5140       uint64_t NVal = -C->getSExtValue();
5141       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5142         CVal = C->getSExtValue();
5143         break;
5144       }
5145       return;
5146     }
5147     // The K and L constraints apply *only* to logical immediates, including
5148     // what used to be the MOVI alias for ORR (though the MOVI alias has now
5149     // been removed and MOV should be used). So these constraints have to
5150     // distinguish between bit patterns that are valid 32-bit or 64-bit
5151     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5152     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5153     // versa.
5154     case 'K':
5155       if (AArch64_AM::isLogicalImmediate(CVal, 32))
5156         break;
5157       return;
5158     case 'L':
5159       if (AArch64_AM::isLogicalImmediate(CVal, 64))
5160         break;
5161       return;
5162     // The M and N constraints are a superset of K and L respectively, for use
5163     // with the MOV (immediate) alias. As well as the logical immediates they
5164     // also match 32 or 64-bit immediates that can be loaded either using a
5165     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5166     // (M) or 64-bit 0x1234000000000000 (N) etc.
5167     // As a note some of this code is liberally stolen from the asm parser.
5168     case 'M': {
5169       if (!isUInt<32>(CVal))
5170         return;
5171       if (AArch64_AM::isLogicalImmediate(CVal, 32))
5172         break;
5173       if ((CVal & 0xFFFF) == CVal)
5174         break;
5175       if ((CVal & 0xFFFF0000ULL) == CVal)
5176         break;
5177       uint64_t NCVal = ~(uint32_t)CVal;
5178       if ((NCVal & 0xFFFFULL) == NCVal)
5179         break;
5180       if ((NCVal & 0xFFFF0000ULL) == NCVal)
5181         break;
5182       return;
5183     }
5184     case 'N': {
5185       if (AArch64_AM::isLogicalImmediate(CVal, 64))
5186         break;
5187       if ((CVal & 0xFFFFULL) == CVal)
5188         break;
5189       if ((CVal & 0xFFFF0000ULL) == CVal)
5190         break;
5191       if ((CVal & 0xFFFF00000000ULL) == CVal)
5192         break;
5193       if ((CVal & 0xFFFF000000000000ULL) == CVal)
5194         break;
5195       uint64_t NCVal = ~CVal;
5196       if ((NCVal & 0xFFFFULL) == NCVal)
5197         break;
5198       if ((NCVal & 0xFFFF0000ULL) == NCVal)
5199         break;
5200       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5201         break;
5202       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5203         break;
5204       return;
5205     }
5206     default:
5207       return;
5208     }
5209
5210     // All assembler immediates are 64-bit integers.
5211     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
5212     break;
5213   }
5214
5215   if (Result.getNode()) {
5216     Ops.push_back(Result);
5217     return;
5218   }
5219
5220   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5221 }
5222
5223 //===----------------------------------------------------------------------===//
5224 //                     AArch64 Advanced SIMD Support
5225 //===----------------------------------------------------------------------===//
5226
5227 /// WidenVector - Given a value in the V64 register class, produce the
5228 /// equivalent value in the V128 register class.
5229 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5230   EVT VT = V64Reg.getValueType();
5231   unsigned NarrowSize = VT.getVectorNumElements();
5232   MVT EltTy = VT.getVectorElementType().getSimpleVT();
5233   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5234   SDLoc DL(V64Reg);
5235
5236   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
5237                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
5238 }
5239
5240 /// getExtFactor - Determine the adjustment factor for the position when
5241 /// generating an "extract from vector registers" instruction.
5242 static unsigned getExtFactor(SDValue &V) {
5243   EVT EltType = V.getValueType().getVectorElementType();
5244   return EltType.getSizeInBits() / 8;
5245 }
5246
5247 /// NarrowVector - Given a value in the V128 register class, produce the
5248 /// equivalent value in the V64 register class.
5249 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5250   EVT VT = V128Reg.getValueType();
5251   unsigned WideSize = VT.getVectorNumElements();
5252   MVT EltTy = VT.getVectorElementType().getSimpleVT();
5253   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5254   SDLoc DL(V128Reg);
5255
5256   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5257 }
5258
5259 // Gather data to see if the operation can be modelled as a
5260 // shuffle in combination with VEXTs.
5261 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5262                                                   SelectionDAG &DAG) const {
5263   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5264   SDLoc dl(Op);
5265   EVT VT = Op.getValueType();
5266   unsigned NumElts = VT.getVectorNumElements();
5267
5268   struct ShuffleSourceInfo {
5269     SDValue Vec;
5270     unsigned MinElt;
5271     unsigned MaxElt;
5272
5273     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5274     // be compatible with the shuffle we intend to construct. As a result
5275     // ShuffleVec will be some sliding window into the original Vec.
5276     SDValue ShuffleVec;
5277
5278     // Code should guarantee that element i in Vec starts at element "WindowBase
5279     // + i * WindowScale in ShuffleVec".
5280     int WindowBase;
5281     int WindowScale;
5282
5283     ShuffleSourceInfo(SDValue Vec)
5284       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5285           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5286
5287     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5288   };
5289
5290   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5291   // node.
5292   SmallVector<ShuffleSourceInfo, 2> Sources;
5293   for (unsigned i = 0; i < NumElts; ++i) {
5294     SDValue V = Op.getOperand(i);
5295     if (V.isUndef())
5296       continue;
5297     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5298              !isa<ConstantSDNode>(V.getOperand(1))) {
5299       // A shuffle can only come from building a vector from various
5300       // elements of other vectors, provided their indices are constant.
5301       return SDValue();
5302     }
5303
5304     // Add this element source to the list if it's not already there.
5305     SDValue SourceVec = V.getOperand(0);
5306     auto Source = find(Sources, SourceVec);
5307     if (Source == Sources.end())
5308       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5309
5310     // Update the minimum and maximum lane number seen.
5311     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5312     Source->MinElt = std::min(Source->MinElt, EltNo);
5313     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5314   }
5315
5316   // Currently only do something sane when at most two source vectors
5317   // are involved.
5318   if (Sources.size() > 2)
5319     return SDValue();
5320
5321   // Find out the smallest element size among result and two sources, and use
5322   // it as element size to build the shuffle_vector.
5323   EVT SmallestEltTy = VT.getVectorElementType();
5324   for (auto &Source : Sources) {
5325     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5326     if (SrcEltTy.bitsLT(SmallestEltTy)) {
5327       SmallestEltTy = SrcEltTy;
5328     }
5329   }
5330   unsigned ResMultiplier =
5331       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
5332   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5333   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5334
5335   // If the source vector is too wide or too narrow, we may nevertheless be able
5336   // to construct a compatible shuffle either by concatenating it with UNDEF or
5337   // extracting a suitable range of elements.
5338   for (auto &Src : Sources) {
5339     EVT SrcVT = Src.ShuffleVec.getValueType();
5340
5341     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5342       continue;
5343
5344     // This stage of the search produces a source with the same element type as
5345     // the original, but with a total width matching the BUILD_VECTOR output.
5346     EVT EltVT = SrcVT.getVectorElementType();
5347     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5348     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5349
5350     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5351       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
5352       // We can pad out the smaller vector for free, so if it's part of a
5353       // shuffle...
5354       Src.ShuffleVec =
5355           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5356                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5357       continue;
5358     }
5359
5360     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
5361
5362     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5363       // Span too large for a VEXT to cope
5364       return SDValue();
5365     }
5366
5367     if (Src.MinElt >= NumSrcElts) {
5368       // The extraction can just take the second half
5369       Src.ShuffleVec =
5370           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5371                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5372       Src.WindowBase = -NumSrcElts;
5373     } else if (Src.MaxElt < NumSrcElts) {
5374       // The extraction can just take the first half
5375       Src.ShuffleVec =
5376           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5377                       DAG.getConstant(0, dl, MVT::i64));
5378     } else {
5379       // An actual VEXT is needed
5380       SDValue VEXTSrc1 =
5381           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5382                       DAG.getConstant(0, dl, MVT::i64));
5383       SDValue VEXTSrc2 =
5384           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5385                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
5386       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5387
5388       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
5389                                    VEXTSrc2,
5390                                    DAG.getConstant(Imm, dl, MVT::i32));
5391       Src.WindowBase = -Src.MinElt;
5392     }
5393   }
5394
5395   // Another possible incompatibility occurs from the vector element types. We
5396   // can fix this by bitcasting the source vectors to the same type we intend
5397   // for the shuffle.
5398   for (auto &Src : Sources) {
5399     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5400     if (SrcEltTy == SmallestEltTy)
5401       continue;
5402     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5403     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5404     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5405     Src.WindowBase *= Src.WindowScale;
5406   }
5407
5408   // Final sanity check before we try to actually produce a shuffle.
5409   DEBUG(
5410     for (auto Src : Sources)
5411       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5412   );
5413
5414   // The stars all align, our next step is to produce the mask for the shuffle.
5415   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5416   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
5417   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5418     SDValue Entry = Op.getOperand(i);
5419     if (Entry.isUndef())
5420       continue;
5421
5422     auto Src = find(Sources, Entry.getOperand(0));
5423     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5424
5425     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5426     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5427     // segment.
5428     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5429     int BitsDefined =
5430         std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
5431     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5432
5433     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5434     // starting at the appropriate offset.
5435     int *LaneMask = &Mask[i * ResMultiplier];
5436
5437     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5438     ExtractBase += NumElts * (Src - Sources.begin());
5439     for (int j = 0; j < LanesDefined; ++j)
5440       LaneMask[j] = ExtractBase + j;
5441   }
5442
5443   // Final check before we try to produce nonsense...
5444   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5445     return SDValue();
5446
5447   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5448   for (unsigned i = 0; i < Sources.size(); ++i)
5449     ShuffleOps[i] = Sources[i].ShuffleVec;
5450
5451   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5452                                          ShuffleOps[1], Mask);
5453   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5454 }
5455
5456 // check if an EXT instruction can handle the shuffle mask when the
5457 // vector sources of the shuffle are the same.
5458 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5459   unsigned NumElts = VT.getVectorNumElements();
5460
5461   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5462   if (M[0] < 0)
5463     return false;
5464
5465   Imm = M[0];
5466
5467   // If this is a VEXT shuffle, the immediate value is the index of the first
5468   // element.  The other shuffle indices must be the successive elements after
5469   // the first one.
5470   unsigned ExpectedElt = Imm;
5471   for (unsigned i = 1; i < NumElts; ++i) {
5472     // Increment the expected index.  If it wraps around, just follow it
5473     // back to index zero and keep going.
5474     ++ExpectedElt;
5475     if (ExpectedElt == NumElts)
5476       ExpectedElt = 0;
5477
5478     if (M[i] < 0)
5479       continue; // ignore UNDEF indices
5480     if (ExpectedElt != static_cast<unsigned>(M[i]))
5481       return false;
5482   }
5483
5484   return true;
5485 }
5486
5487 // check if an EXT instruction can handle the shuffle mask when the
5488 // vector sources of the shuffle are different.
5489 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5490                       unsigned &Imm) {
5491   // Look for the first non-undef element.
5492   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
5493
5494   // Benefit form APInt to handle overflow when calculating expected element.
5495   unsigned NumElts = VT.getVectorNumElements();
5496   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5497   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5498   // The following shuffle indices must be the successive elements after the
5499   // first real element.
5500   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5501       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5502   if (FirstWrongElt != M.end())
5503     return false;
5504
5505   // The index of an EXT is the first element if it is not UNDEF.
5506   // Watch out for the beginning UNDEFs. The EXT index should be the expected
5507   // value of the first element.  E.g.
5508   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5509   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5510   // ExpectedElt is the last mask index plus 1.
5511   Imm = ExpectedElt.getZExtValue();
5512
5513   // There are two difference cases requiring to reverse input vectors.
5514   // For example, for vector <4 x i32> we have the following cases,
5515   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5516   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5517   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5518   // to reverse two input vectors.
5519   if (Imm < NumElts)
5520     ReverseEXT = true;
5521   else
5522     Imm -= NumElts;
5523
5524   return true;
5525 }
5526
5527 /// isREVMask - Check if a vector shuffle corresponds to a REV
5528 /// instruction with the specified blocksize.  (The order of the elements
5529 /// within each block of the vector is reversed.)
5530 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5531   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5532          "Only possible block sizes for REV are: 16, 32, 64");
5533
5534   unsigned EltSz = VT.getScalarSizeInBits();
5535   if (EltSz == 64)
5536     return false;
5537
5538   unsigned NumElts = VT.getVectorNumElements();
5539   unsigned BlockElts = M[0] + 1;
5540   // If the first shuffle index is UNDEF, be optimistic.
5541   if (M[0] < 0)
5542     BlockElts = BlockSize / EltSz;
5543
5544   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5545     return false;
5546
5547   for (unsigned i = 0; i < NumElts; ++i) {
5548     if (M[i] < 0)
5549       continue; // ignore UNDEF indices
5550     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5551       return false;
5552   }
5553
5554   return true;
5555 }
5556
5557 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5558   unsigned NumElts = VT.getVectorNumElements();
5559   WhichResult = (M[0] == 0 ? 0 : 1);
5560   unsigned Idx = WhichResult * NumElts / 2;
5561   for (unsigned i = 0; i != NumElts; i += 2) {
5562     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5563         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5564       return false;
5565     Idx += 1;
5566   }
5567
5568   return true;
5569 }
5570
5571 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5572   unsigned NumElts = VT.getVectorNumElements();
5573   WhichResult = (M[0] == 0 ? 0 : 1);
5574   for (unsigned i = 0; i != NumElts; ++i) {
5575     if (M[i] < 0)
5576       continue; // ignore UNDEF indices
5577     if ((unsigned)M[i] != 2 * i + WhichResult)
5578       return false;
5579   }
5580
5581   return true;
5582 }
5583
5584 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5585   unsigned NumElts = VT.getVectorNumElements();
5586   WhichResult = (M[0] == 0 ? 0 : 1);
5587   for (unsigned i = 0; i < NumElts; i += 2) {
5588     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5589         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5590       return false;
5591   }
5592   return true;
5593 }
5594
5595 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5596 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5597 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5598 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5599   unsigned NumElts = VT.getVectorNumElements();
5600   WhichResult = (M[0] == 0 ? 0 : 1);
5601   unsigned Idx = WhichResult * NumElts / 2;
5602   for (unsigned i = 0; i != NumElts; i += 2) {
5603     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5604         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5605       return false;
5606     Idx += 1;
5607   }
5608
5609   return true;
5610 }
5611
5612 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5613 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5614 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5615 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5616   unsigned Half = VT.getVectorNumElements() / 2;
5617   WhichResult = (M[0] == 0 ? 0 : 1);
5618   for (unsigned j = 0; j != 2; ++j) {
5619     unsigned Idx = WhichResult;
5620     for (unsigned i = 0; i != Half; ++i) {
5621       int MIdx = M[i + j * Half];
5622       if (MIdx >= 0 && (unsigned)MIdx != Idx)
5623         return false;
5624       Idx += 2;
5625     }
5626   }
5627
5628   return true;
5629 }
5630
5631 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5632 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5633 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5634 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5635   unsigned NumElts = VT.getVectorNumElements();
5636   WhichResult = (M[0] == 0 ? 0 : 1);
5637   for (unsigned i = 0; i < NumElts; i += 2) {
5638     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5639         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5640       return false;
5641   }
5642   return true;
5643 }
5644
5645 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5646                       bool &DstIsLeft, int &Anomaly) {
5647   if (M.size() != static_cast<size_t>(NumInputElements))
5648     return false;
5649
5650   int NumLHSMatch = 0, NumRHSMatch = 0;
5651   int LastLHSMismatch = -1, LastRHSMismatch = -1;
5652
5653   for (int i = 0; i < NumInputElements; ++i) {
5654     if (M[i] == -1) {
5655       ++NumLHSMatch;
5656       ++NumRHSMatch;
5657       continue;
5658     }
5659
5660     if (M[i] == i)
5661       ++NumLHSMatch;
5662     else
5663       LastLHSMismatch = i;
5664
5665     if (M[i] == i + NumInputElements)
5666       ++NumRHSMatch;
5667     else
5668       LastRHSMismatch = i;
5669   }
5670
5671   if (NumLHSMatch == NumInputElements - 1) {
5672     DstIsLeft = true;
5673     Anomaly = LastLHSMismatch;
5674     return true;
5675   } else if (NumRHSMatch == NumInputElements - 1) {
5676     DstIsLeft = false;
5677     Anomaly = LastRHSMismatch;
5678     return true;
5679   }
5680
5681   return false;
5682 }
5683
5684 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5685   if (VT.getSizeInBits() != 128)
5686     return false;
5687
5688   unsigned NumElts = VT.getVectorNumElements();
5689
5690   for (int I = 0, E = NumElts / 2; I != E; I++) {
5691     if (Mask[I] != I)
5692       return false;
5693   }
5694
5695   int Offset = NumElts / 2;
5696   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5697     if (Mask[I] != I + SplitLHS * Offset)
5698       return false;
5699   }
5700
5701   return true;
5702 }
5703
5704 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5705   SDLoc DL(Op);
5706   EVT VT = Op.getValueType();
5707   SDValue V0 = Op.getOperand(0);
5708   SDValue V1 = Op.getOperand(1);
5709   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5710
5711   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5712       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5713     return SDValue();
5714
5715   bool SplitV0 = V0.getValueSizeInBits() == 128;
5716
5717   if (!isConcatMask(Mask, VT, SplitV0))
5718     return SDValue();
5719
5720   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5721                                 VT.getVectorNumElements() / 2);
5722   if (SplitV0) {
5723     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5724                      DAG.getConstant(0, DL, MVT::i64));
5725   }
5726   if (V1.getValueSizeInBits() == 128) {
5727     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5728                      DAG.getConstant(0, DL, MVT::i64));
5729   }
5730   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5731 }
5732
5733 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5734 /// the specified operations to build the shuffle.
5735 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5736                                       SDValue RHS, SelectionDAG &DAG,
5737                                       const SDLoc &dl) {
5738   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5739   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5740   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5741
5742   enum {
5743     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5744     OP_VREV,
5745     OP_VDUP0,
5746     OP_VDUP1,
5747     OP_VDUP2,
5748     OP_VDUP3,
5749     OP_VEXT1,
5750     OP_VEXT2,
5751     OP_VEXT3,
5752     OP_VUZPL, // VUZP, left result
5753     OP_VUZPR, // VUZP, right result
5754     OP_VZIPL, // VZIP, left result
5755     OP_VZIPR, // VZIP, right result
5756     OP_VTRNL, // VTRN, left result
5757     OP_VTRNR  // VTRN, right result
5758   };
5759
5760   if (OpNum == OP_COPY) {
5761     if (LHSID == (1 * 9 + 2) * 9 + 3)
5762       return LHS;
5763     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5764     return RHS;
5765   }
5766
5767   SDValue OpLHS, OpRHS;
5768   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5769   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5770   EVT VT = OpLHS.getValueType();
5771
5772   switch (OpNum) {
5773   default:
5774     llvm_unreachable("Unknown shuffle opcode!");
5775   case OP_VREV:
5776     // VREV divides the vector in half and swaps within the half.
5777     if (VT.getVectorElementType() == MVT::i32 ||
5778         VT.getVectorElementType() == MVT::f32)
5779       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5780     // vrev <4 x i16> -> REV32
5781     if (VT.getVectorElementType() == MVT::i16 ||
5782         VT.getVectorElementType() == MVT::f16)
5783       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5784     // vrev <4 x i8> -> REV16
5785     assert(VT.getVectorElementType() == MVT::i8);
5786     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5787   case OP_VDUP0:
5788   case OP_VDUP1:
5789   case OP_VDUP2:
5790   case OP_VDUP3: {
5791     EVT EltTy = VT.getVectorElementType();
5792     unsigned Opcode;
5793     if (EltTy == MVT::i8)
5794       Opcode = AArch64ISD::DUPLANE8;
5795     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5796       Opcode = AArch64ISD::DUPLANE16;
5797     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5798       Opcode = AArch64ISD::DUPLANE32;
5799     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5800       Opcode = AArch64ISD::DUPLANE64;
5801     else
5802       llvm_unreachable("Invalid vector element type?");
5803
5804     if (VT.getSizeInBits() == 64)
5805       OpLHS = WidenVector(OpLHS, DAG);
5806     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5807     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5808   }
5809   case OP_VEXT1:
5810   case OP_VEXT2:
5811   case OP_VEXT3: {
5812     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5813     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5814                        DAG.getConstant(Imm, dl, MVT::i32));
5815   }
5816   case OP_VUZPL:
5817     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5818                        OpRHS);
5819   case OP_VUZPR:
5820     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5821                        OpRHS);
5822   case OP_VZIPL:
5823     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5824                        OpRHS);
5825   case OP_VZIPR:
5826     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5827                        OpRHS);
5828   case OP_VTRNL:
5829     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5830                        OpRHS);
5831   case OP_VTRNR:
5832     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5833                        OpRHS);
5834   }
5835 }
5836
5837 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5838                            SelectionDAG &DAG) {
5839   // Check to see if we can use the TBL instruction.
5840   SDValue V1 = Op.getOperand(0);
5841   SDValue V2 = Op.getOperand(1);
5842   SDLoc DL(Op);
5843
5844   EVT EltVT = Op.getValueType().getVectorElementType();
5845   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5846
5847   SmallVector<SDValue, 8> TBLMask;
5848   for (int Val : ShuffleMask) {
5849     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5850       unsigned Offset = Byte + Val * BytesPerElt;
5851       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5852     }
5853   }
5854
5855   MVT IndexVT = MVT::v8i8;
5856   unsigned IndexLen = 8;
5857   if (Op.getValueSizeInBits() == 128) {
5858     IndexVT = MVT::v16i8;
5859     IndexLen = 16;
5860   }
5861
5862   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5863   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5864
5865   SDValue Shuffle;
5866   if (V2.getNode()->isUndef()) {
5867     if (IndexLen == 8)
5868       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5869     Shuffle = DAG.getNode(
5870         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5871         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5872         DAG.getBuildVector(IndexVT, DL,
5873                            makeArrayRef(TBLMask.data(), IndexLen)));
5874   } else {
5875     if (IndexLen == 8) {
5876       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5877       Shuffle = DAG.getNode(
5878           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5879           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5880           DAG.getBuildVector(IndexVT, DL,
5881                              makeArrayRef(TBLMask.data(), IndexLen)));
5882     } else {
5883       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5884       // cannot currently represent the register constraints on the input
5885       // table registers.
5886       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5887       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
5888       //                   IndexLen));
5889       Shuffle = DAG.getNode(
5890           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5891           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
5892           V2Cst, DAG.getBuildVector(IndexVT, DL,
5893                                     makeArrayRef(TBLMask.data(), IndexLen)));
5894     }
5895   }
5896   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5897 }
5898
5899 static unsigned getDUPLANEOp(EVT EltType) {
5900   if (EltType == MVT::i8)
5901     return AArch64ISD::DUPLANE8;
5902   if (EltType == MVT::i16 || EltType == MVT::f16)
5903     return AArch64ISD::DUPLANE16;
5904   if (EltType == MVT::i32 || EltType == MVT::f32)
5905     return AArch64ISD::DUPLANE32;
5906   if (EltType == MVT::i64 || EltType == MVT::f64)
5907     return AArch64ISD::DUPLANE64;
5908
5909   llvm_unreachable("Invalid vector element type?");
5910 }
5911
5912 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5913                                                    SelectionDAG &DAG) const {
5914   SDLoc dl(Op);
5915   EVT VT = Op.getValueType();
5916
5917   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5918
5919   // Convert shuffles that are directly supported on NEON to target-specific
5920   // DAG nodes, instead of keeping them as shuffles and matching them again
5921   // during code selection.  This is more efficient and avoids the possibility
5922   // of inconsistencies between legalization and selection.
5923   ArrayRef<int> ShuffleMask = SVN->getMask();
5924
5925   SDValue V1 = Op.getOperand(0);
5926   SDValue V2 = Op.getOperand(1);
5927
5928   if (SVN->isSplat()) {
5929     int Lane = SVN->getSplatIndex();
5930     // If this is undef splat, generate it via "just" vdup, if possible.
5931     if (Lane == -1)
5932       Lane = 0;
5933
5934     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5935       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5936                          V1.getOperand(0));
5937     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5938     // constant. If so, we can just reference the lane's definition directly.
5939     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5940         !isa<ConstantSDNode>(V1.getOperand(Lane)))
5941       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5942
5943     // Otherwise, duplicate from the lane of the input vector.
5944     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5945
5946     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5947     // to make a vector of the same size as this SHUFFLE. We can ignore the
5948     // extract entirely, and canonicalise the concat using WidenVector.
5949     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5950       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5951       V1 = V1.getOperand(0);
5952     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5953       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5954       Lane -= Idx * VT.getVectorNumElements() / 2;
5955       V1 = WidenVector(V1.getOperand(Idx), DAG);
5956     } else if (VT.getSizeInBits() == 64)
5957       V1 = WidenVector(V1, DAG);
5958
5959     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5960   }
5961
5962   if (isREVMask(ShuffleMask, VT, 64))
5963     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5964   if (isREVMask(ShuffleMask, VT, 32))
5965     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5966   if (isREVMask(ShuffleMask, VT, 16))
5967     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5968
5969   bool ReverseEXT = false;
5970   unsigned Imm;
5971   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5972     if (ReverseEXT)
5973       std::swap(V1, V2);
5974     Imm *= getExtFactor(V1);
5975     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5976                        DAG.getConstant(Imm, dl, MVT::i32));
5977   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5978     Imm *= getExtFactor(V1);
5979     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5980                        DAG.getConstant(Imm, dl, MVT::i32));
5981   }
5982
5983   unsigned WhichResult;
5984   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5985     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5986     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5987   }
5988   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5989     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5990     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5991   }
5992   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5993     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5994     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5995   }
5996
5997   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5998     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5999     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6000   }
6001   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6002     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6003     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6004   }
6005   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6006     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6007     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6008   }
6009
6010   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
6011     return Concat;
6012
6013   bool DstIsLeft;
6014   int Anomaly;
6015   int NumInputElements = V1.getValueType().getVectorNumElements();
6016   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6017     SDValue DstVec = DstIsLeft ? V1 : V2;
6018     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
6019
6020     SDValue SrcVec = V1;
6021     int SrcLane = ShuffleMask[Anomaly];
6022     if (SrcLane >= NumInputElements) {
6023       SrcVec = V2;
6024       SrcLane -= VT.getVectorNumElements();
6025     }
6026     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
6027
6028     EVT ScalarVT = VT.getVectorElementType();
6029
6030     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
6031       ScalarVT = MVT::i32;
6032
6033     return DAG.getNode(
6034         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6035         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6036         DstLaneV);
6037   }
6038
6039   // If the shuffle is not directly supported and it has 4 elements, use
6040   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6041   unsigned NumElts = VT.getVectorNumElements();
6042   if (NumElts == 4) {
6043     unsigned PFIndexes[4];
6044     for (unsigned i = 0; i != 4; ++i) {
6045       if (ShuffleMask[i] < 0)
6046         PFIndexes[i] = 8;
6047       else
6048         PFIndexes[i] = ShuffleMask[i];
6049     }
6050
6051     // Compute the index in the perfect shuffle table.
6052     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6053                             PFIndexes[2] * 9 + PFIndexes[3];
6054     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6055     unsigned Cost = (PFEntry >> 30);
6056
6057     if (Cost <= 4)
6058       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6059   }
6060
6061   return GenerateTBL(Op, ShuffleMask, DAG);
6062 }
6063
6064 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6065                                APInt &UndefBits) {
6066   EVT VT = BVN->getValueType(0);
6067   APInt SplatBits, SplatUndef;
6068   unsigned SplatBitSize;
6069   bool HasAnyUndefs;
6070   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6071     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6072
6073     for (unsigned i = 0; i < NumSplats; ++i) {
6074       CnstBits <<= SplatBitSize;
6075       UndefBits <<= SplatBitSize;
6076       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6077       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6078     }
6079
6080     return true;
6081   }
6082
6083   return false;
6084 }
6085
6086 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
6087                                               SelectionDAG &DAG) const {
6088   BuildVectorSDNode *BVN =
6089       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6090   SDValue LHS = Op.getOperand(0);
6091   SDLoc dl(Op);
6092   EVT VT = Op.getValueType();
6093
6094   if (!BVN)
6095     return Op;
6096
6097   APInt CnstBits(VT.getSizeInBits(), 0);
6098   APInt UndefBits(VT.getSizeInBits(), 0);
6099   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6100     // We only have BIC vector immediate instruction, which is and-not.
6101     CnstBits = ~CnstBits;
6102
6103     // We make use of a little bit of goto ickiness in order to avoid having to
6104     // duplicate the immediate matching logic for the undef toggled case.
6105     bool SecondTry = false;
6106   AttemptModImm:
6107
6108     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6109       CnstBits = CnstBits.zextOrTrunc(64);
6110       uint64_t CnstVal = CnstBits.getZExtValue();
6111
6112       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6113         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6114         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6115         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6116                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6117                                   DAG.getConstant(0, dl, MVT::i32));
6118         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6119       }
6120
6121       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6122         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6123         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6124         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6125                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6126                                   DAG.getConstant(8, dl, MVT::i32));
6127         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6128       }
6129
6130       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6131         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6132         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6133         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6134                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6135                                   DAG.getConstant(16, dl, MVT::i32));
6136         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6137       }
6138
6139       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6140         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6141         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6142         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6143                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6144                                   DAG.getConstant(24, dl, MVT::i32));
6145         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6146       }
6147
6148       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6149         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6150         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6151         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6152                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6153                                   DAG.getConstant(0, dl, MVT::i32));
6154         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6155       }
6156
6157       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6158         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6159         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6160         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6161                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6162                                   DAG.getConstant(8, dl, MVT::i32));
6163         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6164       }
6165     }
6166
6167     if (SecondTry)
6168       goto FailedModImm;
6169     SecondTry = true;
6170     CnstBits = ~UndefBits;
6171     goto AttemptModImm;
6172   }
6173
6174 // We can always fall back to a non-immediate AND.
6175 FailedModImm:
6176   return Op;
6177 }
6178
6179 // Specialized code to quickly find if PotentialBVec is a BuildVector that
6180 // consists of only the same constant int value, returned in reference arg
6181 // ConstVal
6182 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6183                                      uint64_t &ConstVal) {
6184   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6185   if (!Bvec)
6186     return false;
6187   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6188   if (!FirstElt)
6189     return false;
6190   EVT VT = Bvec->getValueType(0);
6191   unsigned NumElts = VT.getVectorNumElements();
6192   for (unsigned i = 1; i < NumElts; ++i)
6193     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6194       return false;
6195   ConstVal = FirstElt->getZExtValue();
6196   return true;
6197 }
6198
6199 static unsigned getIntrinsicID(const SDNode *N) {
6200   unsigned Opcode = N->getOpcode();
6201   switch (Opcode) {
6202   default:
6203     return Intrinsic::not_intrinsic;
6204   case ISD::INTRINSIC_WO_CHAIN: {
6205     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6206     if (IID < Intrinsic::num_intrinsics)
6207       return IID;
6208     return Intrinsic::not_intrinsic;
6209   }
6210   }
6211 }
6212
6213 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6214 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6215 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6216 // Also, logical shift right -> sri, with the same structure.
6217 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6218   EVT VT = N->getValueType(0);
6219
6220   if (!VT.isVector())
6221     return SDValue();
6222
6223   SDLoc DL(N);
6224
6225   // Is the first op an AND?
6226   const SDValue And = N->getOperand(0);
6227   if (And.getOpcode() != ISD::AND)
6228     return SDValue();
6229
6230   // Is the second op an shl or lshr?
6231   SDValue Shift = N->getOperand(1);
6232   // This will have been turned into: AArch64ISD::VSHL vector, #shift
6233   // or AArch64ISD::VLSHR vector, #shift
6234   unsigned ShiftOpc = Shift.getOpcode();
6235   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6236     return SDValue();
6237   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
6238
6239   // Is the shift amount constant?
6240   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
6241   if (!C2node)
6242     return SDValue();
6243
6244   // Is the and mask vector all constant?
6245   uint64_t C1;
6246   if (!isAllConstantBuildVector(And.getOperand(1), C1))
6247     return SDValue();
6248
6249   // Is C1 == ~C2, taking into account how much one can shift elements of a
6250   // particular size?
6251   uint64_t C2 = C2node->getZExtValue();
6252   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
6253   if (C2 > ElemSizeInBits)
6254     return SDValue();
6255   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
6256   if ((C1 & ElemMask) != (~C2 & ElemMask))
6257     return SDValue();
6258
6259   SDValue X = And.getOperand(0);
6260   SDValue Y = Shift.getOperand(0);
6261
6262   unsigned Intrin =
6263       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
6264   SDValue ResultSLI =
6265       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6266                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
6267                   Shift.getOperand(1));
6268
6269   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
6270   DEBUG(N->dump(&DAG));
6271   DEBUG(dbgs() << "into: \n");
6272   DEBUG(ResultSLI->dump(&DAG));
6273
6274   ++NumShiftInserts;
6275   return ResultSLI;
6276 }
6277
6278 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
6279                                              SelectionDAG &DAG) const {
6280   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
6281   if (EnableAArch64SlrGeneration) {
6282     if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
6283       return Res;
6284   }
6285
6286   BuildVectorSDNode *BVN =
6287       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6288   SDValue LHS = Op.getOperand(1);
6289   SDLoc dl(Op);
6290   EVT VT = Op.getValueType();
6291
6292   // OR commutes, so try swapping the operands.
6293   if (!BVN) {
6294     LHS = Op.getOperand(0);
6295     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6296   }
6297   if (!BVN)
6298     return Op;
6299
6300   APInt CnstBits(VT.getSizeInBits(), 0);
6301   APInt UndefBits(VT.getSizeInBits(), 0);
6302   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6303     // We make use of a little bit of goto ickiness in order to avoid having to
6304     // duplicate the immediate matching logic for the undef toggled case.
6305     bool SecondTry = false;
6306   AttemptModImm:
6307
6308     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6309       CnstBits = CnstBits.zextOrTrunc(64);
6310       uint64_t CnstVal = CnstBits.getZExtValue();
6311
6312       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6313         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6314         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6315         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6316                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6317                                   DAG.getConstant(0, dl, MVT::i32));
6318         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6319       }
6320
6321       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6322         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6323         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6324         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6325                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6326                                   DAG.getConstant(8, dl, MVT::i32));
6327         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6328       }
6329
6330       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6331         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6332         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6333         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6334                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6335                                   DAG.getConstant(16, dl, MVT::i32));
6336         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6337       }
6338
6339       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6340         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6341         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6342         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6343                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6344                                   DAG.getConstant(24, dl, MVT::i32));
6345         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6346       }
6347
6348       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6349         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6350         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6351         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6352                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6353                                   DAG.getConstant(0, dl, MVT::i32));
6354         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6355       }
6356
6357       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6358         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6359         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6360         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6361                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6362                                   DAG.getConstant(8, dl, MVT::i32));
6363         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6364       }
6365     }
6366
6367     if (SecondTry)
6368       goto FailedModImm;
6369     SecondTry = true;
6370     CnstBits = UndefBits;
6371     goto AttemptModImm;
6372   }
6373
6374 // We can always fall back to a non-immediate OR.
6375 FailedModImm:
6376   return Op;
6377 }
6378
6379 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
6380 // be truncated to fit element width.
6381 static SDValue NormalizeBuildVector(SDValue Op,
6382                                     SelectionDAG &DAG) {
6383   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6384   SDLoc dl(Op);
6385   EVT VT = Op.getValueType();
6386   EVT EltTy= VT.getVectorElementType();
6387
6388   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6389     return Op;
6390
6391   SmallVector<SDValue, 16> Ops;
6392   for (SDValue Lane : Op->ops()) {
6393     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
6394       APInt LowBits(EltTy.getSizeInBits(),
6395                     CstLane->getZExtValue());
6396       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
6397     }
6398     Ops.push_back(Lane);
6399   }
6400   return DAG.getBuildVector(VT, dl, Ops);
6401 }
6402
6403 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6404                                                  SelectionDAG &DAG) const {
6405   SDLoc dl(Op);
6406   EVT VT = Op.getValueType();
6407   Op = NormalizeBuildVector(Op, DAG);
6408   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6409
6410   APInt CnstBits(VT.getSizeInBits(), 0);
6411   APInt UndefBits(VT.getSizeInBits(), 0);
6412   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6413     // We make use of a little bit of goto ickiness in order to avoid having to
6414     // duplicate the immediate matching logic for the undef toggled case.
6415     bool SecondTry = false;
6416   AttemptModImm:
6417
6418     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6419       CnstBits = CnstBits.zextOrTrunc(64);
6420       uint64_t CnstVal = CnstBits.getZExtValue();
6421
6422       // Certain magic vector constants (used to express things like NOT
6423       // and NEG) are passed through unmodified.  This allows codegen patterns
6424       // for these operations to match.  Special-purpose patterns will lower
6425       // these immediates to MOVIs if it proves necessary.
6426       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6427         return Op;
6428
6429       // The many faces of MOVI...
6430       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6431         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6432         if (VT.getSizeInBits() == 128) {
6433           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
6434                                     DAG.getConstant(CnstVal, dl, MVT::i32));
6435           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6436         }
6437
6438         // Support the V64 version via subregister insertion.
6439         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
6440                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6441         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6442       }
6443
6444       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6445         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6446         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6447         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6448                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6449                                   DAG.getConstant(0, dl, MVT::i32));
6450         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6451       }
6452
6453       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6454         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6455         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6456         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6457                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6458                                   DAG.getConstant(8, dl, MVT::i32));
6459         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6460       }
6461
6462       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6463         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6464         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6465         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6466                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6467                                   DAG.getConstant(16, dl, MVT::i32));
6468         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6469       }
6470
6471       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6472         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6473         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6474         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6475                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6476                                   DAG.getConstant(24, dl, MVT::i32));
6477         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6478       }
6479
6480       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6481         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6482         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6483         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6484                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6485                                   DAG.getConstant(0, dl, MVT::i32));
6486         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6487       }
6488
6489       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6490         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6491         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6492         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6493                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6494                                   DAG.getConstant(8, dl, MVT::i32));
6495         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6496       }
6497
6498       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6499         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6500         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6501         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6502                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6503                                   DAG.getConstant(264, dl, MVT::i32));
6504         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6505       }
6506
6507       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6508         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6509         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6510         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6511                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6512                                   DAG.getConstant(272, dl, MVT::i32));
6513         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6514       }
6515
6516       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6517         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6518         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6519         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6520                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6521         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6522       }
6523
6524       // The few faces of FMOV...
6525       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6526         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6527         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6528         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6529                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6530         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6531       }
6532
6533       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6534           VT.getSizeInBits() == 128) {
6535         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6536         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6537                                   DAG.getConstant(CnstVal, dl, MVT::i32));
6538         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6539       }
6540
6541       // The many faces of MVNI...
6542       CnstVal = ~CnstVal;
6543       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6544         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6545         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6546         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6547                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6548                                   DAG.getConstant(0, dl, MVT::i32));
6549         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6550       }
6551
6552       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6553         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6554         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6555         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6556                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6557                                   DAG.getConstant(8, dl, MVT::i32));
6558         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6559       }
6560
6561       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6562         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6563         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6564         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6565                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6566                                   DAG.getConstant(16, dl, MVT::i32));
6567         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6568       }
6569
6570       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6571         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6572         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6573         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6574                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6575                                   DAG.getConstant(24, dl, MVT::i32));
6576         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6577       }
6578
6579       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6580         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6581         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6582         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6583                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6584                                   DAG.getConstant(0, dl, MVT::i32));
6585         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6586       }
6587
6588       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6589         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6590         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6591         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6592                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6593                                   DAG.getConstant(8, dl, MVT::i32));
6594         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6595       }
6596
6597       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6598         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6599         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6600         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6601                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6602                                   DAG.getConstant(264, dl, MVT::i32));
6603         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6604       }
6605
6606       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6607         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6608         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6609         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6610                                   DAG.getConstant(CnstVal, dl, MVT::i32),
6611                                   DAG.getConstant(272, dl, MVT::i32));
6612         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6613       }
6614     }
6615
6616     if (SecondTry)
6617       goto FailedModImm;
6618     SecondTry = true;
6619     CnstBits = UndefBits;
6620     goto AttemptModImm;
6621   }
6622 FailedModImm:
6623
6624   // Scan through the operands to find some interesting properties we can
6625   // exploit:
6626   //   1) If only one value is used, we can use a DUP, or
6627   //   2) if only the low element is not undef, we can just insert that, or
6628   //   3) if only one constant value is used (w/ some non-constant lanes),
6629   //      we can splat the constant value into the whole vector then fill
6630   //      in the non-constant lanes.
6631   //   4) FIXME: If different constant values are used, but we can intelligently
6632   //             select the values we'll be overwriting for the non-constant
6633   //             lanes such that we can directly materialize the vector
6634   //             some other way (MOVI, e.g.), we can be sneaky.
6635   unsigned NumElts = VT.getVectorNumElements();
6636   bool isOnlyLowElement = true;
6637   bool usesOnlyOneValue = true;
6638   bool usesOnlyOneConstantValue = true;
6639   bool isConstant = true;
6640   unsigned NumConstantLanes = 0;
6641   SDValue Value;
6642   SDValue ConstantValue;
6643   for (unsigned i = 0; i < NumElts; ++i) {
6644     SDValue V = Op.getOperand(i);
6645     if (V.isUndef())
6646       continue;
6647     if (i > 0)
6648       isOnlyLowElement = false;
6649     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6650       isConstant = false;
6651
6652     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6653       ++NumConstantLanes;
6654       if (!ConstantValue.getNode())
6655         ConstantValue = V;
6656       else if (ConstantValue != V)
6657         usesOnlyOneConstantValue = false;
6658     }
6659
6660     if (!Value.getNode())
6661       Value = V;
6662     else if (V != Value)
6663       usesOnlyOneValue = false;
6664   }
6665
6666   if (!Value.getNode())
6667     return DAG.getUNDEF(VT);
6668
6669   if (isOnlyLowElement)
6670     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6671
6672   // Use DUP for non-constant splats.  For f32 constant splats, reduce to
6673   // i32 and try again.
6674   if (usesOnlyOneValue) {
6675     if (!isConstant) {
6676       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6677           Value.getValueType() != VT)
6678         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6679
6680       // This is actually a DUPLANExx operation, which keeps everything vectory.
6681
6682       // DUPLANE works on 128-bit vectors, widen it if necessary.
6683       SDValue Lane = Value.getOperand(1);
6684       Value = Value.getOperand(0);
6685       if (Value.getValueSizeInBits() == 64)
6686         Value = WidenVector(Value, DAG);
6687
6688       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6689       return DAG.getNode(Opcode, dl, VT, Value, Lane);
6690     }
6691
6692     if (VT.getVectorElementType().isFloatingPoint()) {
6693       SmallVector<SDValue, 8> Ops;
6694       EVT EltTy = VT.getVectorElementType();
6695       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6696               "Unsupported floating-point vector type");
6697       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6698       for (unsigned i = 0; i < NumElts; ++i)
6699         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6700       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6701       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6702       Val = LowerBUILD_VECTOR(Val, DAG);
6703       if (Val.getNode())
6704         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6705     }
6706   }
6707
6708   // If there was only one constant value used and for more than one lane,
6709   // start by splatting that value, then replace the non-constant lanes. This
6710   // is better than the default, which will perform a separate initialization
6711   // for each lane.
6712   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6713     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6714     // Now insert the non-constant lanes.
6715     for (unsigned i = 0; i < NumElts; ++i) {
6716       SDValue V = Op.getOperand(i);
6717       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6718       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6719         // Note that type legalization likely mucked about with the VT of the
6720         // source operand, so we may have to convert it here before inserting.
6721         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6722       }
6723     }
6724     return Val;
6725   }
6726
6727   // If all elements are constants and the case above didn't get hit, fall back
6728   // to the default expansion, which will generate a load from the constant
6729   // pool.
6730   if (isConstant)
6731     return SDValue();
6732
6733   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6734   if (NumElts >= 4) {
6735     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6736       return shuffle;
6737   }
6738
6739   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6740   // know the default expansion would otherwise fall back on something even
6741   // worse. For a vector with one or two non-undef values, that's
6742   // scalar_to_vector for the elements followed by a shuffle (provided the
6743   // shuffle is valid for the target) and materialization element by element
6744   // on the stack followed by a load for everything else.
6745   if (!isConstant && !usesOnlyOneValue) {
6746     SDValue Vec = DAG.getUNDEF(VT);
6747     SDValue Op0 = Op.getOperand(0);
6748     unsigned i = 0;
6749
6750     // Use SCALAR_TO_VECTOR for lane zero to
6751     // a) Avoid a RMW dependency on the full vector register, and
6752     // b) Allow the register coalescer to fold away the copy if the
6753     //    value is already in an S or D register, and we're forced to emit an
6754     //    INSERT_SUBREG that we can't fold anywhere.
6755     //
6756     // We also allow types like i8 and i16 which are illegal scalar but legal
6757     // vector element types. After type-legalization the inserted value is
6758     // extended (i32) and it is safe to cast them to the vector type by ignoring
6759     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
6760     if (!Op0.isUndef()) {
6761       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
6762       ++i;
6763     }
6764     for (; i < NumElts; ++i) {
6765       SDValue V = Op.getOperand(i);
6766       if (V.isUndef())
6767         continue;
6768       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6769       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6770     }
6771     return Vec;
6772   }
6773
6774   // Just use the default expansion. We failed to find a better alternative.
6775   return SDValue();
6776 }
6777
6778 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6779                                                       SelectionDAG &DAG) const {
6780   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6781
6782   // Check for non-constant or out of range lane.
6783   EVT VT = Op.getOperand(0).getValueType();
6784   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6785   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6786     return SDValue();
6787
6788
6789   // Insertion/extraction are legal for V128 types.
6790   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6791       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6792       VT == MVT::v8f16)
6793     return Op;
6794
6795   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6796       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6797     return SDValue();
6798
6799   // For V64 types, we perform insertion by expanding the value
6800   // to a V128 type and perform the insertion on that.
6801   SDLoc DL(Op);
6802   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6803   EVT WideTy = WideVec.getValueType();
6804
6805   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6806                              Op.getOperand(1), Op.getOperand(2));
6807   // Re-narrow the resultant vector.
6808   return NarrowVector(Node, DAG);
6809 }
6810
6811 SDValue
6812 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6813                                                SelectionDAG &DAG) const {
6814   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6815
6816   // Check for non-constant or out of range lane.
6817   EVT VT = Op.getOperand(0).getValueType();
6818   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6819   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6820     return SDValue();
6821
6822
6823   // Insertion/extraction are legal for V128 types.
6824   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6825       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6826       VT == MVT::v8f16)
6827     return Op;
6828
6829   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6830       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6831     return SDValue();
6832
6833   // For V64 types, we perform extraction by expanding the value
6834   // to a V128 type and perform the extraction on that.
6835   SDLoc DL(Op);
6836   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6837   EVT WideTy = WideVec.getValueType();
6838
6839   EVT ExtrTy = WideTy.getVectorElementType();
6840   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6841     ExtrTy = MVT::i32;
6842
6843   // For extractions, we just return the result directly.
6844   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6845                      Op.getOperand(1));
6846 }
6847
6848 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6849                                                       SelectionDAG &DAG) const {
6850   EVT VT = Op.getOperand(0).getValueType();
6851   SDLoc dl(Op);
6852   // Just in case...
6853   if (!VT.isVector())
6854     return SDValue();
6855
6856   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6857   if (!Cst)
6858     return SDValue();
6859   unsigned Val = Cst->getZExtValue();
6860
6861   unsigned Size = Op.getValueSizeInBits();
6862
6863   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6864   if (Val == 0)
6865     return Op;
6866
6867   // If this is extracting the upper 64-bits of a 128-bit vector, we match
6868   // that directly.
6869   if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
6870     return Op;
6871
6872   return SDValue();
6873 }
6874
6875 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6876                                                EVT VT) const {
6877   if (VT.getVectorNumElements() == 4 &&
6878       (VT.is128BitVector() || VT.is64BitVector())) {
6879     unsigned PFIndexes[4];
6880     for (unsigned i = 0; i != 4; ++i) {
6881       if (M[i] < 0)
6882         PFIndexes[i] = 8;
6883       else
6884         PFIndexes[i] = M[i];
6885     }
6886
6887     // Compute the index in the perfect shuffle table.
6888     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6889                             PFIndexes[2] * 9 + PFIndexes[3];
6890     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6891     unsigned Cost = (PFEntry >> 30);
6892
6893     if (Cost <= 4)
6894       return true;
6895   }
6896
6897   bool DummyBool;
6898   int DummyInt;
6899   unsigned DummyUnsigned;
6900
6901   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6902           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6903           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6904           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6905           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6906           isZIPMask(M, VT, DummyUnsigned) ||
6907           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6908           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6909           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6910           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6911           isConcatMask(M, VT, VT.getSizeInBits() == 128));
6912 }
6913
6914 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6915 /// operand of a vector shift operation, where all the elements of the
6916 /// build_vector must have the same constant integer value.
6917 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6918   // Ignore bit_converts.
6919   while (Op.getOpcode() == ISD::BITCAST)
6920     Op = Op.getOperand(0);
6921   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6922   APInt SplatBits, SplatUndef;
6923   unsigned SplatBitSize;
6924   bool HasAnyUndefs;
6925   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6926                                     HasAnyUndefs, ElementBits) ||
6927       SplatBitSize > ElementBits)
6928     return false;
6929   Cnt = SplatBits.getSExtValue();
6930   return true;
6931 }
6932
6933 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6934 /// operand of a vector shift left operation.  That value must be in the range:
6935 ///   0 <= Value < ElementBits for a left shift; or
6936 ///   0 <= Value <= ElementBits for a long left shift.
6937 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6938   assert(VT.isVector() && "vector shift count is not a vector type");
6939   int64_t ElementBits = VT.getScalarSizeInBits();
6940   if (!getVShiftImm(Op, ElementBits, Cnt))
6941     return false;
6942   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6943 }
6944
6945 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6946 /// operand of a vector shift right operation. The value must be in the range:
6947 ///   1 <= Value <= ElementBits for a right shift; or
6948 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6949   assert(VT.isVector() && "vector shift count is not a vector type");
6950   int64_t ElementBits = VT.getScalarSizeInBits();
6951   if (!getVShiftImm(Op, ElementBits, Cnt))
6952     return false;
6953   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6954 }
6955
6956 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6957                                                       SelectionDAG &DAG) const {
6958   EVT VT = Op.getValueType();
6959   SDLoc DL(Op);
6960   int64_t Cnt;
6961
6962   if (!Op.getOperand(1).getValueType().isVector())
6963     return Op;
6964   unsigned EltSize = VT.getScalarSizeInBits();
6965
6966   switch (Op.getOpcode()) {
6967   default:
6968     llvm_unreachable("unexpected shift opcode");
6969
6970   case ISD::SHL:
6971     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6972       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6973                          DAG.getConstant(Cnt, DL, MVT::i32));
6974     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6975                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6976                                        MVT::i32),
6977                        Op.getOperand(0), Op.getOperand(1));
6978   case ISD::SRA:
6979   case ISD::SRL:
6980     // Right shift immediate
6981     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6982       unsigned Opc =
6983           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6984       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6985                          DAG.getConstant(Cnt, DL, MVT::i32));
6986     }
6987
6988     // Right shift register.  Note, there is not a shift right register
6989     // instruction, but the shift left register instruction takes a signed
6990     // value, where negative numbers specify a right shift.
6991     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6992                                                 : Intrinsic::aarch64_neon_ushl;
6993     // negate the shift amount
6994     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6995     SDValue NegShiftLeft =
6996         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6997                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6998                     NegShift);
6999     return NegShiftLeft;
7000   }
7001
7002   return SDValue();
7003 }
7004
7005 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7006                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
7007                                     const SDLoc &dl, SelectionDAG &DAG) {
7008   EVT SrcVT = LHS.getValueType();
7009   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7010          "function only supposed to emit natural comparisons");
7011
7012   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7013   APInt CnstBits(VT.getSizeInBits(), 0);
7014   APInt UndefBits(VT.getSizeInBits(), 0);
7015   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7016   bool IsZero = IsCnst && (CnstBits == 0);
7017
7018   if (SrcVT.getVectorElementType().isFloatingPoint()) {
7019     switch (CC) {
7020     default:
7021       return SDValue();
7022     case AArch64CC::NE: {
7023       SDValue Fcmeq;
7024       if (IsZero)
7025         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7026       else
7027         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7028       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7029     }
7030     case AArch64CC::EQ:
7031       if (IsZero)
7032         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7033       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7034     case AArch64CC::GE:
7035       if (IsZero)
7036         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7037       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7038     case AArch64CC::GT:
7039       if (IsZero)
7040         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7041       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7042     case AArch64CC::LS:
7043       if (IsZero)
7044         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7045       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7046     case AArch64CC::LT:
7047       if (!NoNans)
7048         return SDValue();
7049       // If we ignore NaNs then we can use to the MI implementation.
7050       LLVM_FALLTHROUGH;
7051     case AArch64CC::MI:
7052       if (IsZero)
7053         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7054       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7055     }
7056   }
7057
7058   switch (CC) {
7059   default:
7060     return SDValue();
7061   case AArch64CC::NE: {
7062     SDValue Cmeq;
7063     if (IsZero)
7064       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7065     else
7066       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7067     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7068   }
7069   case AArch64CC::EQ:
7070     if (IsZero)
7071       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7072     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7073   case AArch64CC::GE:
7074     if (IsZero)
7075       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7076     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7077   case AArch64CC::GT:
7078     if (IsZero)
7079       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7080     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7081   case AArch64CC::LE:
7082     if (IsZero)
7083       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7084     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7085   case AArch64CC::LS:
7086     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7087   case AArch64CC::LO:
7088     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7089   case AArch64CC::LT:
7090     if (IsZero)
7091       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7092     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7093   case AArch64CC::HI:
7094     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7095   case AArch64CC::HS:
7096     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7097   }
7098 }
7099
7100 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7101                                            SelectionDAG &DAG) const {
7102   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7103   SDValue LHS = Op.getOperand(0);
7104   SDValue RHS = Op.getOperand(1);
7105   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
7106   SDLoc dl(Op);
7107
7108   if (LHS.getValueType().getVectorElementType().isInteger()) {
7109     assert(LHS.getValueType() == RHS.getValueType());
7110     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
7111     SDValue Cmp =
7112         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7113     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7114   }
7115
7116   if (LHS.getValueType().getVectorElementType() == MVT::f16)
7117     return SDValue();
7118
7119   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
7120          LHS.getValueType().getVectorElementType() == MVT::f64);
7121
7122   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7123   // clean.  Some of them require two branches to implement.
7124   AArch64CC::CondCode CC1, CC2;
7125   bool ShouldInvert;
7126   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7127
7128   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7129   SDValue Cmp =
7130       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
7131   if (!Cmp.getNode())
7132     return SDValue();
7133
7134   if (CC2 != AArch64CC::AL) {
7135     SDValue Cmp2 =
7136         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
7137     if (!Cmp2.getNode())
7138       return SDValue();
7139
7140     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
7141   }
7142
7143   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7144
7145   if (ShouldInvert)
7146     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
7147
7148   return Cmp;
7149 }
7150
7151 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7152                                   SelectionDAG &DAG) {
7153   SDValue VecOp = ScalarOp.getOperand(0);
7154   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7155   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7156                      DAG.getConstant(0, DL, MVT::i64));
7157 }
7158
7159 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7160                                               SelectionDAG &DAG) const {
7161   SDLoc dl(Op);
7162   switch (Op.getOpcode()) {
7163   case ISD::VECREDUCE_ADD:
7164     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7165   case ISD::VECREDUCE_SMAX:
7166     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7167   case ISD::VECREDUCE_SMIN:
7168     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
7169   case ISD::VECREDUCE_UMAX:
7170     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
7171   case ISD::VECREDUCE_UMIN:
7172     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
7173   case ISD::VECREDUCE_FMAX: {
7174     assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7175     return DAG.getNode(
7176         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7177         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
7178         Op.getOperand(0));
7179   }
7180   case ISD::VECREDUCE_FMIN: {
7181     assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7182     return DAG.getNode(
7183         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7184         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
7185         Op.getOperand(0));
7186   }
7187   default:
7188     llvm_unreachable("Unhandled reduction");
7189   }
7190 }
7191
7192 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
7193 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
7194 /// specified in the intrinsic calls.
7195 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
7196                                                const CallInst &I,
7197                                                unsigned Intrinsic) const {
7198   auto &DL = I.getModule()->getDataLayout();
7199   switch (Intrinsic) {
7200   case Intrinsic::aarch64_neon_ld2:
7201   case Intrinsic::aarch64_neon_ld3:
7202   case Intrinsic::aarch64_neon_ld4:
7203   case Intrinsic::aarch64_neon_ld1x2:
7204   case Intrinsic::aarch64_neon_ld1x3:
7205   case Intrinsic::aarch64_neon_ld1x4:
7206   case Intrinsic::aarch64_neon_ld2lane:
7207   case Intrinsic::aarch64_neon_ld3lane:
7208   case Intrinsic::aarch64_neon_ld4lane:
7209   case Intrinsic::aarch64_neon_ld2r:
7210   case Intrinsic::aarch64_neon_ld3r:
7211   case Intrinsic::aarch64_neon_ld4r: {
7212     Info.opc = ISD::INTRINSIC_W_CHAIN;
7213     // Conservatively set memVT to the entire set of vectors loaded.
7214     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
7215     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7216     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7217     Info.offset = 0;
7218     Info.align = 0;
7219     Info.vol = false; // volatile loads with NEON intrinsics not supported
7220     Info.readMem = true;
7221     Info.writeMem = false;
7222     return true;
7223   }
7224   case Intrinsic::aarch64_neon_st2:
7225   case Intrinsic::aarch64_neon_st3:
7226   case Intrinsic::aarch64_neon_st4:
7227   case Intrinsic::aarch64_neon_st1x2:
7228   case Intrinsic::aarch64_neon_st1x3:
7229   case Intrinsic::aarch64_neon_st1x4:
7230   case Intrinsic::aarch64_neon_st2lane:
7231   case Intrinsic::aarch64_neon_st3lane:
7232   case Intrinsic::aarch64_neon_st4lane: {
7233     Info.opc = ISD::INTRINSIC_VOID;
7234     // Conservatively set memVT to the entire set of vectors stored.
7235     unsigned NumElts = 0;
7236     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
7237       Type *ArgTy = I.getArgOperand(ArgI)->getType();
7238       if (!ArgTy->isVectorTy())
7239         break;
7240       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
7241     }
7242     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7243     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7244     Info.offset = 0;
7245     Info.align = 0;
7246     Info.vol = false; // volatile stores with NEON intrinsics not supported
7247     Info.readMem = false;
7248     Info.writeMem = true;
7249     return true;
7250   }
7251   case Intrinsic::aarch64_ldaxr:
7252   case Intrinsic::aarch64_ldxr: {
7253     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
7254     Info.opc = ISD::INTRINSIC_W_CHAIN;
7255     Info.memVT = MVT::getVT(PtrTy->getElementType());
7256     Info.ptrVal = I.getArgOperand(0);
7257     Info.offset = 0;
7258     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7259     Info.vol = true;
7260     Info.readMem = true;
7261     Info.writeMem = false;
7262     return true;
7263   }
7264   case Intrinsic::aarch64_stlxr:
7265   case Intrinsic::aarch64_stxr: {
7266     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
7267     Info.opc = ISD::INTRINSIC_W_CHAIN;
7268     Info.memVT = MVT::getVT(PtrTy->getElementType());
7269     Info.ptrVal = I.getArgOperand(1);
7270     Info.offset = 0;
7271     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7272     Info.vol = true;
7273     Info.readMem = false;
7274     Info.writeMem = true;
7275     return true;
7276   }
7277   case Intrinsic::aarch64_ldaxp:
7278   case Intrinsic::aarch64_ldxp:
7279     Info.opc = ISD::INTRINSIC_W_CHAIN;
7280     Info.memVT = MVT::i128;
7281     Info.ptrVal = I.getArgOperand(0);
7282     Info.offset = 0;
7283     Info.align = 16;
7284     Info.vol = true;
7285     Info.readMem = true;
7286     Info.writeMem = false;
7287     return true;
7288   case Intrinsic::aarch64_stlxp:
7289   case Intrinsic::aarch64_stxp:
7290     Info.opc = ISD::INTRINSIC_W_CHAIN;
7291     Info.memVT = MVT::i128;
7292     Info.ptrVal = I.getArgOperand(2);
7293     Info.offset = 0;
7294     Info.align = 16;
7295     Info.vol = true;
7296     Info.readMem = false;
7297     Info.writeMem = true;
7298     return true;
7299   default:
7300     break;
7301   }
7302
7303   return false;
7304 }
7305
7306 // Truncations from 64-bit GPR to 32-bit GPR is free.
7307 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
7308   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7309     return false;
7310   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7311   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7312   return NumBits1 > NumBits2;
7313 }
7314 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7315   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7316     return false;
7317   unsigned NumBits1 = VT1.getSizeInBits();
7318   unsigned NumBits2 = VT2.getSizeInBits();
7319   return NumBits1 > NumBits2;
7320 }
7321
7322 /// Check if it is profitable to hoist instruction in then/else to if.
7323 /// Not profitable if I and it's user can form a FMA instruction
7324 /// because we prefer FMSUB/FMADD.
7325 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
7326   if (I->getOpcode() != Instruction::FMul)
7327     return true;
7328
7329   if (!I->hasOneUse())
7330     return true;
7331
7332   Instruction *User = I->user_back();
7333
7334   if (User &&
7335       !(User->getOpcode() == Instruction::FSub ||
7336         User->getOpcode() == Instruction::FAdd))
7337     return true;
7338
7339   const TargetOptions &Options = getTargetMachine().Options;
7340   const DataLayout &DL = I->getModule()->getDataLayout();
7341   EVT VT = getValueType(DL, User->getOperand(0)->getType());
7342
7343   return !(isFMAFasterThanFMulAndFAdd(VT) &&
7344            isOperationLegalOrCustom(ISD::FMA, VT) &&
7345            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7346             Options.UnsafeFPMath));
7347 }
7348
7349 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
7350 // 64-bit GPR.
7351 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7352   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7353     return false;
7354   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7355   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7356   return NumBits1 == 32 && NumBits2 == 64;
7357 }
7358 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7359   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7360     return false;
7361   unsigned NumBits1 = VT1.getSizeInBits();
7362   unsigned NumBits2 = VT2.getSizeInBits();
7363   return NumBits1 == 32 && NumBits2 == 64;
7364 }
7365
7366 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7367   EVT VT1 = Val.getValueType();
7368   if (isZExtFree(VT1, VT2)) {
7369     return true;
7370   }
7371
7372   if (Val.getOpcode() != ISD::LOAD)
7373     return false;
7374
7375   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
7376   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7377           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7378           VT1.getSizeInBits() <= 32);
7379 }
7380
7381 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7382   if (isa<FPExtInst>(Ext))
7383     return false;
7384
7385   // Vector types are next free.
7386   if (Ext->getType()->isVectorTy())
7387     return false;
7388
7389   for (const Use &U : Ext->uses()) {
7390     // The extension is free if we can fold it with a left shift in an
7391     // addressing mode or an arithmetic operation: add, sub, and cmp.
7392
7393     // Is there a shift?
7394     const Instruction *Instr = cast<Instruction>(U.getUser());
7395
7396     // Is this a constant shift?
7397     switch (Instr->getOpcode()) {
7398     case Instruction::Shl:
7399       if (!isa<ConstantInt>(Instr->getOperand(1)))
7400         return false;
7401       break;
7402     case Instruction::GetElementPtr: {
7403       gep_type_iterator GTI = gep_type_begin(Instr);
7404       auto &DL = Ext->getModule()->getDataLayout();
7405       std::advance(GTI, U.getOperandNo()-1);
7406       Type *IdxTy = GTI.getIndexedType();
7407       // This extension will end up with a shift because of the scaling factor.
7408       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7409       // Get the shift amount based on the scaling factor:
7410       // log2(sizeof(IdxTy)) - log2(8).
7411       uint64_t ShiftAmt =
7412           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
7413       // Is the constant foldable in the shift of the addressing mode?
7414       // I.e., shift amount is between 1 and 4 inclusive.
7415       if (ShiftAmt == 0 || ShiftAmt > 4)
7416         return false;
7417       break;
7418     }
7419     case Instruction::Trunc:
7420       // Check if this is a noop.
7421       // trunc(sext ty1 to ty2) to ty1.
7422       if (Instr->getType() == Ext->getOperand(0)->getType())
7423         continue;
7424       LLVM_FALLTHROUGH;
7425     default:
7426       return false;
7427     }
7428
7429     // At this point we can use the bfm family, so this extension is free
7430     // for that use.
7431   }
7432   return true;
7433 }
7434
7435 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7436                                           unsigned &RequiredAligment) const {
7437   if (!LoadedType.isSimple() ||
7438       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7439     return false;
7440   // Cyclone supports unaligned accesses.
7441   RequiredAligment = 0;
7442   unsigned NumBits = LoadedType.getSizeInBits();
7443   return NumBits == 32 || NumBits == 64;
7444 }
7445
7446 /// A helper function for determining the number of interleaved accesses we
7447 /// will generate when lowering accesses of the given type.
7448 unsigned
7449 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
7450                                                  const DataLayout &DL) const {
7451   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
7452 }
7453
7454 bool AArch64TargetLowering::isLegalInterleavedAccessType(
7455     VectorType *VecTy, const DataLayout &DL) const {
7456
7457   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7458   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
7459
7460   // Ensure the number of vector elements is greater than 1.
7461   if (VecTy->getNumElements() < 2)
7462     return false;
7463
7464   // Ensure the element type is legal.
7465   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
7466     return false;
7467
7468   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
7469   // 128 will be split into multiple interleaved accesses.
7470   return VecSize == 64 || VecSize % 128 == 0;
7471 }
7472
7473 /// \brief Lower an interleaved load into a ldN intrinsic.
7474 ///
7475 /// E.g. Lower an interleaved load (Factor = 2):
7476 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7477 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
7478 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
7479 ///
7480 ///      Into:
7481 ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7482 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7483 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7484 bool AArch64TargetLowering::lowerInterleavedLoad(
7485     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7486     ArrayRef<unsigned> Indices, unsigned Factor) const {
7487   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7488          "Invalid interleave factor");
7489   assert(!Shuffles.empty() && "Empty shufflevector input");
7490   assert(Shuffles.size() == Indices.size() &&
7491          "Unmatched number of shufflevectors and indices");
7492
7493   const DataLayout &DL = LI->getModule()->getDataLayout();
7494
7495   VectorType *VecTy = Shuffles[0]->getType();
7496
7497   // Skip if we do not have NEON and skip illegal vector types. We can
7498   // "legalize" wide vector types into multiple interleaved accesses as long as
7499   // the vector types are divisible by 128.
7500   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
7501     return false;
7502
7503   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
7504
7505   // A pointer vector can not be the return type of the ldN intrinsics. Need to
7506   // load integer vectors first and then convert to pointer vectors.
7507   Type *EltTy = VecTy->getVectorElementType();
7508   if (EltTy->isPointerTy())
7509     VecTy =
7510         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7511
7512   IRBuilder<> Builder(LI);
7513
7514   // The base address of the load.
7515   Value *BaseAddr = LI->getPointerOperand();
7516
7517   if (NumLoads > 1) {
7518     // If we're going to generate more than one load, reset the sub-vector type
7519     // to something legal.
7520     VecTy = VectorType::get(VecTy->getVectorElementType(),
7521                             VecTy->getVectorNumElements() / NumLoads);
7522
7523     // We will compute the pointer operand of each load from the original base
7524     // address using GEPs. Cast the base address to a pointer to the scalar
7525     // element type.
7526     BaseAddr = Builder.CreateBitCast(
7527         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
7528                       LI->getPointerAddressSpace()));
7529   }
7530
7531   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7532   Type *Tys[2] = {VecTy, PtrTy};
7533   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7534                                             Intrinsic::aarch64_neon_ld3,
7535                                             Intrinsic::aarch64_neon_ld4};
7536   Function *LdNFunc =
7537       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7538
7539   // Holds sub-vectors extracted from the load intrinsic return values. The
7540   // sub-vectors are associated with the shufflevector instructions they will
7541   // replace.
7542   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
7543
7544   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
7545
7546     // If we're generating more than one load, compute the base address of
7547     // subsequent loads as an offset from the previous.
7548     if (LoadCount > 0)
7549       BaseAddr = Builder.CreateConstGEP1_32(
7550           BaseAddr, VecTy->getVectorNumElements() * Factor);
7551
7552     CallInst *LdN = Builder.CreateCall(
7553         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
7554
7555     // Extract and store the sub-vectors returned by the load intrinsic.
7556     for (unsigned i = 0; i < Shuffles.size(); i++) {
7557       ShuffleVectorInst *SVI = Shuffles[i];
7558       unsigned Index = Indices[i];
7559
7560       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7561
7562       // Convert the integer vector to pointer vector if the element is pointer.
7563       if (EltTy->isPointerTy())
7564         SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7565
7566       SubVecs[SVI].push_back(SubVec);
7567     }
7568   }
7569
7570   // Replace uses of the shufflevector instructions with the sub-vectors
7571   // returned by the load intrinsic. If a shufflevector instruction is
7572   // associated with more than one sub-vector, those sub-vectors will be
7573   // concatenated into a single wide vector.
7574   for (ShuffleVectorInst *SVI : Shuffles) {
7575     auto &SubVec = SubVecs[SVI];
7576     auto *WideVec =
7577         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
7578     SVI->replaceAllUsesWith(WideVec);
7579   }
7580
7581   return true;
7582 }
7583
7584 /// \brief Lower an interleaved store into a stN intrinsic.
7585 ///
7586 /// E.g. Lower an interleaved store (Factor = 3):
7587 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7588 ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7589 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7590 ///
7591 ///      Into:
7592 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7593 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7594 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7595 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7596 ///
7597 /// Note that the new shufflevectors will be removed and we'll only generate one
7598 /// st3 instruction in CodeGen.
7599 ///
7600 /// Example for a more general valid mask (Factor 3). Lower:
7601 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
7602 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
7603 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
7604 ///
7605 ///      Into:
7606 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
7607 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
7608 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
7609 ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7610 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7611                                                   ShuffleVectorInst *SVI,
7612                                                   unsigned Factor) const {
7613   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7614          "Invalid interleave factor");
7615
7616   VectorType *VecTy = SVI->getType();
7617   assert(VecTy->getVectorNumElements() % Factor == 0 &&
7618          "Invalid interleaved store");
7619
7620   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
7621   Type *EltTy = VecTy->getVectorElementType();
7622   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
7623
7624   const DataLayout &DL = SI->getModule()->getDataLayout();
7625
7626   // Skip if we do not have NEON and skip illegal vector types. We can
7627   // "legalize" wide vector types into multiple interleaved accesses as long as
7628   // the vector types are divisible by 128.
7629   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
7630     return false;
7631
7632   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
7633
7634   Value *Op0 = SVI->getOperand(0);
7635   Value *Op1 = SVI->getOperand(1);
7636   IRBuilder<> Builder(SI);
7637
7638   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7639   // vectors to integer vectors.
7640   if (EltTy->isPointerTy()) {
7641     Type *IntTy = DL.getIntPtrType(EltTy);
7642     unsigned NumOpElts =
7643         dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7644
7645     // Convert to the corresponding integer vector.
7646     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7647     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7648     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7649
7650     SubVecTy = VectorType::get(IntTy, LaneLen);
7651   }
7652
7653   // The base address of the store.
7654   Value *BaseAddr = SI->getPointerOperand();
7655
7656   if (NumStores > 1) {
7657     // If we're going to generate more than one store, reset the lane length
7658     // and sub-vector type to something legal.
7659     LaneLen /= NumStores;
7660     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
7661
7662     // We will compute the pointer operand of each store from the original base
7663     // address using GEPs. Cast the base address to a pointer to the scalar
7664     // element type.
7665     BaseAddr = Builder.CreateBitCast(
7666         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
7667                       SI->getPointerAddressSpace()));
7668   }
7669
7670   auto Mask = SVI->getShuffleMask();
7671
7672   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7673   Type *Tys[2] = {SubVecTy, PtrTy};
7674   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7675                                              Intrinsic::aarch64_neon_st3,
7676                                              Intrinsic::aarch64_neon_st4};
7677   Function *StNFunc =
7678       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7679
7680   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
7681
7682     SmallVector<Value *, 5> Ops;
7683
7684     // Split the shufflevector operands into sub vectors for the new stN call.
7685     for (unsigned i = 0; i < Factor; i++) {
7686       unsigned IdxI = StoreCount * LaneLen * Factor + i;
7687       if (Mask[IdxI] >= 0) {
7688         Ops.push_back(Builder.CreateShuffleVector(
7689             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
7690       } else {
7691         unsigned StartMask = 0;
7692         for (unsigned j = 1; j < LaneLen; j++) {
7693           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
7694           if (Mask[IdxJ * Factor + IdxI] >= 0) {
7695             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
7696             break;
7697           }
7698         }
7699         // Note: Filling undef gaps with random elements is ok, since
7700         // those elements were being written anyway (with undefs).
7701         // In the case of all undefs we're defaulting to using elems from 0
7702         // Note: StartMask cannot be negative, it's checked in
7703         // isReInterleaveMask
7704         Ops.push_back(Builder.CreateShuffleVector(
7705             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
7706       }
7707     }
7708
7709     // If we generating more than one store, we compute the base address of
7710     // subsequent stores as an offset from the previous.
7711     if (StoreCount > 0)
7712       BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
7713
7714     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
7715     Builder.CreateCall(StNFunc, Ops);
7716   }
7717   return true;
7718 }
7719
7720 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7721                        unsigned AlignCheck) {
7722   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7723           (DstAlign == 0 || DstAlign % AlignCheck == 0));
7724 }
7725
7726 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7727                                                unsigned SrcAlign, bool IsMemset,
7728                                                bool ZeroMemset,
7729                                                bool MemcpyStrSrc,
7730                                                MachineFunction &MF) const {
7731   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7732   // instruction to materialize the v2i64 zero and one store (with restrictive
7733   // addressing mode). Just do two i64 store of zero-registers.
7734   bool Fast;
7735   const Function *F = MF.getFunction();
7736   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7737       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7738       (memOpAlign(SrcAlign, DstAlign, 16) ||
7739        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7740     return MVT::f128;
7741
7742   if (Size >= 8 &&
7743       (memOpAlign(SrcAlign, DstAlign, 8) ||
7744        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7745     return MVT::i64;
7746
7747   if (Size >= 4 &&
7748       (memOpAlign(SrcAlign, DstAlign, 4) ||
7749        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7750     return MVT::i32;
7751
7752   return MVT::Other;
7753 }
7754
7755 // 12-bit optionally shifted immediates are legal for adds.
7756 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7757   // Avoid UB for INT64_MIN.
7758   if (Immed == std::numeric_limits<int64_t>::min())
7759     return false;
7760   // Same encoding for add/sub, just flip the sign.
7761   Immed = std::abs(Immed);
7762   return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
7763 }
7764
7765 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7766 // immediates is the same as for an add or a sub.
7767 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7768   return isLegalAddImmediate(Immed);
7769 }
7770
7771 /// isLegalAddressingMode - Return true if the addressing mode represented
7772 /// by AM is legal for this target, for a load/store of the specified type.
7773 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7774                                                   const AddrMode &AM, Type *Ty,
7775                                                   unsigned AS) const {
7776   // AArch64 has five basic addressing modes:
7777   //  reg
7778   //  reg + 9-bit signed offset
7779   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
7780   //  reg1 + reg2
7781   //  reg + SIZE_IN_BYTES * reg
7782
7783   // No global is ever allowed as a base.
7784   if (AM.BaseGV)
7785     return false;
7786
7787   // No reg+reg+imm addressing.
7788   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7789     return false;
7790
7791   // check reg + imm case:
7792   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7793   uint64_t NumBytes = 0;
7794   if (Ty->isSized()) {
7795     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7796     NumBytes = NumBits / 8;
7797     if (!isPowerOf2_64(NumBits))
7798       NumBytes = 0;
7799   }
7800
7801   if (!AM.Scale) {
7802     int64_t Offset = AM.BaseOffs;
7803
7804     // 9-bit signed offset
7805     if (isInt<9>(Offset))
7806       return true;
7807
7808     // 12-bit unsigned offset
7809     unsigned shift = Log2_64(NumBytes);
7810     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7811         // Must be a multiple of NumBytes (NumBytes is a power of 2)
7812         (Offset >> shift) << shift == Offset)
7813       return true;
7814     return false;
7815   }
7816
7817   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7818
7819   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
7820 }
7821
7822 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7823                                                 const AddrMode &AM, Type *Ty,
7824                                                 unsigned AS) const {
7825   // Scaling factors are not free at all.
7826   // Operands                     | Rt Latency
7827   // -------------------------------------------
7828   // Rt, [Xn, Xm]                 | 4
7829   // -------------------------------------------
7830   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
7831   // Rt, [Xn, Wm, <extend> #imm]  |
7832   if (isLegalAddressingMode(DL, AM, Ty, AS))
7833     // Scale represents reg2 * scale, thus account for 1 if
7834     // it is not equal to 0 or 1.
7835     return AM.Scale != 0 && AM.Scale != 1;
7836   return -1;
7837 }
7838
7839 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7840   VT = VT.getScalarType();
7841
7842   if (!VT.isSimple())
7843     return false;
7844
7845   switch (VT.getSimpleVT().SimpleTy) {
7846   case MVT::f32:
7847   case MVT::f64:
7848     return true;
7849   default:
7850     break;
7851   }
7852
7853   return false;
7854 }
7855
7856 const MCPhysReg *
7857 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7858   // LR is a callee-save register, but we must treat it as clobbered by any call
7859   // site. Hence we include LR in the scratch registers, which are in turn added
7860   // as implicit-defs for stackmaps and patchpoints.
7861   static const MCPhysReg ScratchRegs[] = {
7862     AArch64::X16, AArch64::X17, AArch64::LR, 0
7863   };
7864   return ScratchRegs;
7865 }
7866
7867 bool
7868 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7869   EVT VT = N->getValueType(0);
7870     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7871     // it with shift to let it be lowered to UBFX.
7872   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7873       isa<ConstantSDNode>(N->getOperand(1))) {
7874     uint64_t TruncMask = N->getConstantOperandVal(1);
7875     if (isMask_64(TruncMask) &&
7876       N->getOperand(0).getOpcode() == ISD::SRL &&
7877       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7878       return false;
7879   }
7880   return true;
7881 }
7882
7883 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7884                                                               Type *Ty) const {
7885   assert(Ty->isIntegerTy());
7886
7887   unsigned BitSize = Ty->getPrimitiveSizeInBits();
7888   if (BitSize == 0)
7889     return false;
7890
7891   int64_t Val = Imm.getSExtValue();
7892   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7893     return true;
7894
7895   if ((int64_t)Val < 0)
7896     Val = ~Val;
7897   if (BitSize == 32)
7898     Val &= (1LL << 32) - 1;
7899
7900   unsigned LZ = countLeadingZeros((uint64_t)Val);
7901   unsigned Shift = (63 - LZ) / 16;
7902   // MOVZ is free so return true for one or fewer MOVK.
7903   return Shift < 3;
7904 }
7905
7906 /// Turn vector tests of the signbit in the form of:
7907 ///   xor (sra X, elt_size(X)-1), -1
7908 /// into:
7909 ///   cmge X, X, #0
7910 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
7911                                          const AArch64Subtarget *Subtarget) {
7912   EVT VT = N->getValueType(0);
7913   if (!Subtarget->hasNEON() || !VT.isVector())
7914     return SDValue();
7915
7916   // There must be a shift right algebraic before the xor, and the xor must be a
7917   // 'not' operation.
7918   SDValue Shift = N->getOperand(0);
7919   SDValue Ones = N->getOperand(1);
7920   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
7921       !ISD::isBuildVectorAllOnes(Ones.getNode()))
7922     return SDValue();
7923
7924   // The shift should be smearing the sign bit across each vector element.
7925   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7926   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
7927   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
7928     return SDValue();
7929
7930   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
7931 }
7932
7933 // Generate SUBS and CSEL for integer abs.
7934 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7935   EVT VT = N->getValueType(0);
7936
7937   SDValue N0 = N->getOperand(0);
7938   SDValue N1 = N->getOperand(1);
7939   SDLoc DL(N);
7940
7941   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7942   // and change it to SUB and CSEL.
7943   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7944       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7945       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7946     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7947       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7948         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7949                                   N0.getOperand(0));
7950         // Generate SUBS & CSEL.
7951         SDValue Cmp =
7952             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7953                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
7954         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7955                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7956                            SDValue(Cmp.getNode(), 1));
7957       }
7958   return SDValue();
7959 }
7960
7961 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7962                                  TargetLowering::DAGCombinerInfo &DCI,
7963                                  const AArch64Subtarget *Subtarget) {
7964   if (DCI.isBeforeLegalizeOps())
7965     return SDValue();
7966
7967   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
7968     return Cmp;
7969
7970   return performIntegerAbsCombine(N, DAG);
7971 }
7972
7973 SDValue
7974 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7975                                      SelectionDAG &DAG,
7976                                      std::vector<SDNode *> *Created) const {
7977   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
7978   if (isIntDivCheap(N->getValueType(0), Attr))
7979     return SDValue(N,0); // Lower SDIV as SDIV
7980
7981   // fold (sdiv X, pow2)
7982   EVT VT = N->getValueType(0);
7983   if ((VT != MVT::i32 && VT != MVT::i64) ||
7984       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7985     return SDValue();
7986
7987   SDLoc DL(N);
7988   SDValue N0 = N->getOperand(0);
7989   unsigned Lg2 = Divisor.countTrailingZeros();
7990   SDValue Zero = DAG.getConstant(0, DL, VT);
7991   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7992
7993   // Add (N0 < 0) ? Pow2 - 1 : 0;
7994   SDValue CCVal;
7995   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7996   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7997   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7998
7999   if (Created) {
8000     Created->push_back(Cmp.getNode());
8001     Created->push_back(Add.getNode());
8002     Created->push_back(CSel.getNode());
8003   }
8004
8005   // Divide by pow2.
8006   SDValue SRA =
8007       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
8008
8009   // If we're dividing by a positive value, we're done.  Otherwise, we must
8010   // negate the result.
8011   if (Divisor.isNonNegative())
8012     return SRA;
8013
8014   if (Created)
8015     Created->push_back(SRA.getNode());
8016   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
8017 }
8018
8019 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
8020                                  TargetLowering::DAGCombinerInfo &DCI,
8021                                  const AArch64Subtarget *Subtarget) {
8022   if (DCI.isBeforeLegalizeOps())
8023     return SDValue();
8024
8025   // The below optimizations require a constant RHS.
8026   if (!isa<ConstantSDNode>(N->getOperand(1)))
8027     return SDValue();
8028
8029   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
8030   const APInt &ConstValue = C->getAPIntValue();
8031
8032   // Multiplication of a power of two plus/minus one can be done more
8033   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
8034   // future CPUs have a cheaper MADD instruction, this may need to be
8035   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
8036   // 64-bit is 5 cycles, so this is always a win.
8037   // More aggressively, some multiplications N0 * C can be lowered to
8038   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
8039   // e.g. 6=3*2=(2+1)*2.
8040   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
8041   // which equals to (1+2)*16-(1+2).
8042   SDValue N0 = N->getOperand(0);
8043   // TrailingZeroes is used to test if the mul can be lowered to
8044   // shift+add+shift.
8045   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
8046   if (TrailingZeroes) {
8047     // Conservatively do not lower to shift+add+shift if the mul might be
8048     // folded into smul or umul.
8049     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
8050                             isZeroExtended(N0.getNode(), DAG)))
8051       return SDValue();
8052     // Conservatively do not lower to shift+add+shift if the mul might be
8053     // folded into madd or msub.
8054     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
8055                            N->use_begin()->getOpcode() == ISD::SUB))
8056       return SDValue();
8057   }
8058   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
8059   // and shift+add+shift.
8060   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
8061
8062   unsigned ShiftAmt, AddSubOpc;
8063   // Is the shifted value the LHS operand of the add/sub?
8064   bool ShiftValUseIsN0 = true;
8065   // Do we need to negate the result?
8066   bool NegateResult = false;
8067
8068   if (ConstValue.isNonNegative()) {
8069     // (mul x, 2^N + 1) => (add (shl x, N), x)
8070     // (mul x, 2^N - 1) => (sub (shl x, N), x)
8071     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
8072     APInt SCVMinus1 = ShiftedConstValue - 1;
8073     APInt CVPlus1 = ConstValue + 1;
8074     if (SCVMinus1.isPowerOf2()) {
8075       ShiftAmt = SCVMinus1.logBase2();
8076       AddSubOpc = ISD::ADD;
8077     } else if (CVPlus1.isPowerOf2()) {
8078       ShiftAmt = CVPlus1.logBase2();
8079       AddSubOpc = ISD::SUB;
8080     } else
8081       return SDValue();
8082   } else {
8083     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8084     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8085     APInt CVNegPlus1 = -ConstValue + 1;
8086     APInt CVNegMinus1 = -ConstValue - 1;
8087     if (CVNegPlus1.isPowerOf2()) {
8088       ShiftAmt = CVNegPlus1.logBase2();
8089       AddSubOpc = ISD::SUB;
8090       ShiftValUseIsN0 = false;
8091     } else if (CVNegMinus1.isPowerOf2()) {
8092       ShiftAmt = CVNegMinus1.logBase2();
8093       AddSubOpc = ISD::ADD;
8094       NegateResult = true;
8095     } else
8096       return SDValue();
8097   }
8098
8099   SDLoc DL(N);
8100   EVT VT = N->getValueType(0);
8101   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
8102                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
8103
8104   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
8105   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
8106   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
8107   assert(!(NegateResult && TrailingZeroes) &&
8108          "NegateResult and TrailingZeroes cannot both be true for now.");
8109   // Negate the result.
8110   if (NegateResult)
8111     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
8112   // Shift the result.
8113   if (TrailingZeroes)
8114     return DAG.getNode(ISD::SHL, DL, VT, Res,
8115                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
8116   return Res;
8117 }
8118
8119 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
8120                                                          SelectionDAG &DAG) {
8121   // Take advantage of vector comparisons producing 0 or -1 in each lane to
8122   // optimize away operation when it's from a constant.
8123   //
8124   // The general transformation is:
8125   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
8126   //       AND(VECTOR_CMP(x,y), constant2)
8127   //    constant2 = UNARYOP(constant)
8128
8129   // Early exit if this isn't a vector operation, the operand of the
8130   // unary operation isn't a bitwise AND, or if the sizes of the operations
8131   // aren't the same.
8132   EVT VT = N->getValueType(0);
8133   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
8134       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
8135       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
8136     return SDValue();
8137
8138   // Now check that the other operand of the AND is a constant. We could
8139   // make the transformation for non-constant splats as well, but it's unclear
8140   // that would be a benefit as it would not eliminate any operations, just
8141   // perform one more step in scalar code before moving to the vector unit.
8142   if (BuildVectorSDNode *BV =
8143           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
8144     // Bail out if the vector isn't a constant.
8145     if (!BV->isConstant())
8146       return SDValue();
8147
8148     // Everything checks out. Build up the new and improved node.
8149     SDLoc DL(N);
8150     EVT IntVT = BV->getValueType(0);
8151     // Create a new constant of the appropriate type for the transformed
8152     // DAG.
8153     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
8154     // The AND node needs bitcasts to/from an integer vector type around it.
8155     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
8156     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
8157                                  N->getOperand(0)->getOperand(0), MaskConst);
8158     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
8159     return Res;
8160   }
8161
8162   return SDValue();
8163 }
8164
8165 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
8166                                      const AArch64Subtarget *Subtarget) {
8167   // First try to optimize away the conversion when it's conditionally from
8168   // a constant. Vectors only.
8169   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
8170     return Res;
8171
8172   EVT VT = N->getValueType(0);
8173   if (VT != MVT::f32 && VT != MVT::f64)
8174     return SDValue();
8175
8176   // Only optimize when the source and destination types have the same width.
8177   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
8178     return SDValue();
8179
8180   // If the result of an integer load is only used by an integer-to-float
8181   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
8182   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
8183   SDValue N0 = N->getOperand(0);
8184   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8185       // Do not change the width of a volatile load.
8186       !cast<LoadSDNode>(N0)->isVolatile()) {
8187     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8188     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8189                                LN0->getPointerInfo(), LN0->getAlignment(),
8190                                LN0->getMemOperand()->getFlags());
8191
8192     // Make sure successors of the original load stay after it by updating them
8193     // to use the new Chain.
8194     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
8195
8196     unsigned Opcode =
8197         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
8198     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
8199   }
8200
8201   return SDValue();
8202 }
8203
8204 /// Fold a floating-point multiply by power of two into floating-point to
8205 /// fixed-point conversion.
8206 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
8207                                      TargetLowering::DAGCombinerInfo &DCI,
8208                                      const AArch64Subtarget *Subtarget) {
8209   if (!Subtarget->hasNEON())
8210     return SDValue();
8211
8212   SDValue Op = N->getOperand(0);
8213   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8214       Op.getOpcode() != ISD::FMUL)
8215     return SDValue();
8216
8217   SDValue ConstVec = Op->getOperand(1);
8218   if (!isa<BuildVectorSDNode>(ConstVec))
8219     return SDValue();
8220
8221   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
8222   uint32_t FloatBits = FloatTy.getSizeInBits();
8223   if (FloatBits != 32 && FloatBits != 64)
8224     return SDValue();
8225
8226   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
8227   uint32_t IntBits = IntTy.getSizeInBits();
8228   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8229     return SDValue();
8230
8231   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
8232   if (IntBits > FloatBits)
8233     return SDValue();
8234
8235   BitVector UndefElements;
8236   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8237   int32_t Bits = IntBits == 64 ? 64 : 32;
8238   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
8239   if (C == -1 || C == 0 || C > Bits)
8240     return SDValue();
8241
8242   MVT ResTy;
8243   unsigned NumLanes = Op.getValueType().getVectorNumElements();
8244   switch (NumLanes) {
8245   default:
8246     return SDValue();
8247   case 2:
8248     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8249     break;
8250   case 4:
8251     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
8252     break;
8253   }
8254
8255   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8256     return SDValue();
8257
8258   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
8259          "Illegal vector type after legalization");
8260
8261   SDLoc DL(N);
8262   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8263   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
8264                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
8265   SDValue FixConv =
8266       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
8267                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
8268                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
8269   // We can handle smaller integers by generating an extra trunc.
8270   if (IntBits < FloatBits)
8271     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
8272
8273   return FixConv;
8274 }
8275
8276 /// Fold a floating-point divide by power of two into fixed-point to
8277 /// floating-point conversion.
8278 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
8279                                   TargetLowering::DAGCombinerInfo &DCI,
8280                                   const AArch64Subtarget *Subtarget) {
8281   if (!Subtarget->hasNEON())
8282     return SDValue();
8283
8284   SDValue Op = N->getOperand(0);
8285   unsigned Opc = Op->getOpcode();
8286   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8287       !Op.getOperand(0).getValueType().isSimple() ||
8288       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
8289     return SDValue();
8290
8291   SDValue ConstVec = N->getOperand(1);
8292   if (!isa<BuildVectorSDNode>(ConstVec))
8293     return SDValue();
8294
8295   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
8296   int32_t IntBits = IntTy.getSizeInBits();
8297   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8298     return SDValue();
8299
8300   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
8301   int32_t FloatBits = FloatTy.getSizeInBits();
8302   if (FloatBits != 32 && FloatBits != 64)
8303     return SDValue();
8304
8305   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
8306   if (IntBits > FloatBits)
8307     return SDValue();
8308
8309   BitVector UndefElements;
8310   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8311   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
8312   if (C == -1 || C == 0 || C > FloatBits)
8313     return SDValue();
8314
8315   MVT ResTy;
8316   unsigned NumLanes = Op.getValueType().getVectorNumElements();
8317   switch (NumLanes) {
8318   default:
8319     return SDValue();
8320   case 2:
8321     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8322     break;
8323   case 4:
8324     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
8325     break;
8326   }
8327
8328   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8329     return SDValue();
8330
8331   SDLoc DL(N);
8332   SDValue ConvInput = Op.getOperand(0);
8333   bool IsSigned = Opc == ISD::SINT_TO_FP;
8334   if (IntBits < FloatBits)
8335     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
8336                             ResTy, ConvInput);
8337
8338   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
8339                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
8340   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
8341                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
8342                      DAG.getConstant(C, DL, MVT::i32));
8343 }
8344
8345 /// An EXTR instruction is made up of two shifts, ORed together. This helper
8346 /// searches for and classifies those shifts.
8347 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
8348                          bool &FromHi) {
8349   if (N.getOpcode() == ISD::SHL)
8350     FromHi = false;
8351   else if (N.getOpcode() == ISD::SRL)
8352     FromHi = true;
8353   else
8354     return false;
8355
8356   if (!isa<ConstantSDNode>(N.getOperand(1)))
8357     return false;
8358
8359   ShiftAmount = N->getConstantOperandVal(1);
8360   Src = N->getOperand(0);
8361   return true;
8362 }
8363
8364 /// EXTR instruction extracts a contiguous chunk of bits from two existing
8365 /// registers viewed as a high/low pair. This function looks for the pattern:
8366 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
8367 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
8368 /// independent.
8369 static SDValue tryCombineToEXTR(SDNode *N,
8370                                 TargetLowering::DAGCombinerInfo &DCI) {
8371   SelectionDAG &DAG = DCI.DAG;
8372   SDLoc DL(N);
8373   EVT VT = N->getValueType(0);
8374
8375   assert(N->getOpcode() == ISD::OR && "Unexpected root");
8376
8377   if (VT != MVT::i32 && VT != MVT::i64)
8378     return SDValue();
8379
8380   SDValue LHS;
8381   uint32_t ShiftLHS = 0;
8382   bool LHSFromHi = false;
8383   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
8384     return SDValue();
8385
8386   SDValue RHS;
8387   uint32_t ShiftRHS = 0;
8388   bool RHSFromHi = false;
8389   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
8390     return SDValue();
8391
8392   // If they're both trying to come from the high part of the register, they're
8393   // not really an EXTR.
8394   if (LHSFromHi == RHSFromHi)
8395     return SDValue();
8396
8397   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
8398     return SDValue();
8399
8400   if (LHSFromHi) {
8401     std::swap(LHS, RHS);
8402     std::swap(ShiftLHS, ShiftRHS);
8403   }
8404
8405   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
8406                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
8407 }
8408
8409 static SDValue tryCombineToBSL(SDNode *N,
8410                                 TargetLowering::DAGCombinerInfo &DCI) {
8411   EVT VT = N->getValueType(0);
8412   SelectionDAG &DAG = DCI.DAG;
8413   SDLoc DL(N);
8414
8415   if (!VT.isVector())
8416     return SDValue();
8417
8418   SDValue N0 = N->getOperand(0);
8419   if (N0.getOpcode() != ISD::AND)
8420     return SDValue();
8421
8422   SDValue N1 = N->getOperand(1);
8423   if (N1.getOpcode() != ISD::AND)
8424     return SDValue();
8425
8426   // We only have to look for constant vectors here since the general, variable
8427   // case can be handled in TableGen.
8428   unsigned Bits = VT.getScalarSizeInBits();
8429   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
8430   for (int i = 1; i >= 0; --i)
8431     for (int j = 1; j >= 0; --j) {
8432       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
8433       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
8434       if (!BVN0 || !BVN1)
8435         continue;
8436
8437       bool FoundMatch = true;
8438       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
8439         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
8440         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
8441         if (!CN0 || !CN1 ||
8442             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
8443           FoundMatch = false;
8444           break;
8445         }
8446       }
8447
8448       if (FoundMatch)
8449         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
8450                            N0->getOperand(1 - i), N1->getOperand(1 - j));
8451     }
8452
8453   return SDValue();
8454 }
8455
8456 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8457                                 const AArch64Subtarget *Subtarget) {
8458   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
8459   SelectionDAG &DAG = DCI.DAG;
8460   EVT VT = N->getValueType(0);
8461
8462   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8463     return SDValue();
8464
8465   if (SDValue Res = tryCombineToEXTR(N, DCI))
8466     return Res;
8467
8468   if (SDValue Res = tryCombineToBSL(N, DCI))
8469     return Res;
8470
8471   return SDValue();
8472 }
8473
8474 static SDValue performSRLCombine(SDNode *N,
8475                                  TargetLowering::DAGCombinerInfo &DCI) {
8476   SelectionDAG &DAG = DCI.DAG;
8477   EVT VT = N->getValueType(0);
8478   if (VT != MVT::i32 && VT != MVT::i64)
8479     return SDValue();
8480
8481   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
8482   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
8483   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
8484   SDValue N0 = N->getOperand(0);
8485   if (N0.getOpcode() == ISD::BSWAP) {
8486     SDLoc DL(N);
8487     SDValue N1 = N->getOperand(1);
8488     SDValue N00 = N0.getOperand(0);
8489     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8490       uint64_t ShiftAmt = C->getZExtValue();
8491       if (VT == MVT::i32 && ShiftAmt == 16 &&
8492           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
8493         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8494       if (VT == MVT::i64 && ShiftAmt == 32 &&
8495           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
8496         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8497     }
8498   }
8499   return SDValue();
8500 }
8501
8502 static SDValue performBitcastCombine(SDNode *N,
8503                                      TargetLowering::DAGCombinerInfo &DCI,
8504                                      SelectionDAG &DAG) {
8505   // Wait 'til after everything is legalized to try this. That way we have
8506   // legal vector types and such.
8507   if (DCI.isBeforeLegalizeOps())
8508     return SDValue();
8509
8510   // Remove extraneous bitcasts around an extract_subvector.
8511   // For example,
8512   //    (v4i16 (bitconvert
8513   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
8514   //  becomes
8515   //    (extract_subvector ((v8i16 ...), (i64 4)))
8516
8517   // Only interested in 64-bit vectors as the ultimate result.
8518   EVT VT = N->getValueType(0);
8519   if (!VT.isVector())
8520     return SDValue();
8521   if (VT.getSimpleVT().getSizeInBits() != 64)
8522     return SDValue();
8523   // Is the operand an extract_subvector starting at the beginning or halfway
8524   // point of the vector? A low half may also come through as an
8525   // EXTRACT_SUBREG, so look for that, too.
8526   SDValue Op0 = N->getOperand(0);
8527   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8528       !(Op0->isMachineOpcode() &&
8529         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8530     return SDValue();
8531   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8532   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8533     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8534       return SDValue();
8535   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8536     if (idx != AArch64::dsub)
8537       return SDValue();
8538     // The dsub reference is equivalent to a lane zero subvector reference.
8539     idx = 0;
8540   }
8541   // Look through the bitcast of the input to the extract.
8542   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8543     return SDValue();
8544   SDValue Source = Op0->getOperand(0)->getOperand(0);
8545   // If the source type has twice the number of elements as our destination
8546   // type, we know this is an extract of the high or low half of the vector.
8547   EVT SVT = Source->getValueType(0);
8548   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8549     return SDValue();
8550
8551   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8552
8553   // Create the simplified form to just extract the low or high half of the
8554   // vector directly rather than bothering with the bitcasts.
8555   SDLoc dl(N);
8556   unsigned NumElements = VT.getVectorNumElements();
8557   if (idx) {
8558     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
8559     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8560   } else {
8561     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
8562     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8563                                       Source, SubReg),
8564                    0);
8565   }
8566 }
8567
8568 static SDValue performConcatVectorsCombine(SDNode *N,
8569                                            TargetLowering::DAGCombinerInfo &DCI,
8570                                            SelectionDAG &DAG) {
8571   SDLoc dl(N);
8572   EVT VT = N->getValueType(0);
8573   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8574
8575   // Optimize concat_vectors of truncated vectors, where the intermediate
8576   // type is illegal, to avoid said illegality,  e.g.,
8577   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8578   //                          (v2i16 (truncate (v2i64)))))
8579   // ->
8580   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8581   //                                    (v4i32 (bitcast (v2i64))),
8582   //                                    <0, 2, 4, 6>)))
8583   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8584   // on both input and result type, so we might generate worse code.
8585   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8586   if (N->getNumOperands() == 2 &&
8587       N0->getOpcode() == ISD::TRUNCATE &&
8588       N1->getOpcode() == ISD::TRUNCATE) {
8589     SDValue N00 = N0->getOperand(0);
8590     SDValue N10 = N1->getOperand(0);
8591     EVT N00VT = N00.getValueType();
8592
8593     if (N00VT == N10.getValueType() &&
8594         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8595         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
8596       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8597       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8598       for (size_t i = 0; i < Mask.size(); ++i)
8599         Mask[i] = i * 2;
8600       return DAG.getNode(ISD::TRUNCATE, dl, VT,
8601                          DAG.getVectorShuffle(
8602                              MidVT, dl,
8603                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8604                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
8605     }
8606   }
8607
8608   // Wait 'til after everything is legalized to try this. That way we have
8609   // legal vector types and such.
8610   if (DCI.isBeforeLegalizeOps())
8611     return SDValue();
8612
8613   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8614   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8615   // canonicalise to that.
8616   if (N0 == N1 && VT.getVectorNumElements() == 2) {
8617     assert(VT.getScalarSizeInBits() == 64);
8618     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
8619                        DAG.getConstant(0, dl, MVT::i64));
8620   }
8621
8622   // Canonicalise concat_vectors so that the right-hand vector has as few
8623   // bit-casts as possible before its real operation. The primary matching
8624   // destination for these operations will be the narrowing "2" instructions,
8625   // which depend on the operation being performed on this right-hand vector.
8626   // For example,
8627   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
8628   // becomes
8629   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8630
8631   if (N1->getOpcode() != ISD::BITCAST)
8632     return SDValue();
8633   SDValue RHS = N1->getOperand(0);
8634   MVT RHSTy = RHS.getValueType().getSimpleVT();
8635   // If the RHS is not a vector, this is not the pattern we're looking for.
8636   if (!RHSTy.isVector())
8637     return SDValue();
8638
8639   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8640
8641   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8642                                   RHSTy.getVectorNumElements() * 2);
8643   return DAG.getNode(ISD::BITCAST, dl, VT,
8644                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8645                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8646                                  RHS));
8647 }
8648
8649 static SDValue tryCombineFixedPointConvert(SDNode *N,
8650                                            TargetLowering::DAGCombinerInfo &DCI,
8651                                            SelectionDAG &DAG) {
8652   // Wait 'til after everything is legalized to try this. That way we have
8653   // legal vector types and such.
8654   if (DCI.isBeforeLegalizeOps())
8655     return SDValue();
8656   // Transform a scalar conversion of a value from a lane extract into a
8657   // lane extract of a vector conversion. E.g., from foo1 to foo2:
8658   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8659   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8660   //
8661   // The second form interacts better with instruction selection and the
8662   // register allocator to avoid cross-class register copies that aren't
8663   // coalescable due to a lane reference.
8664
8665   // Check the operand and see if it originates from a lane extract.
8666   SDValue Op1 = N->getOperand(1);
8667   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8668     // Yep, no additional predication needed. Perform the transform.
8669     SDValue IID = N->getOperand(0);
8670     SDValue Shift = N->getOperand(2);
8671     SDValue Vec = Op1.getOperand(0);
8672     SDValue Lane = Op1.getOperand(1);
8673     EVT ResTy = N->getValueType(0);
8674     EVT VecResTy;
8675     SDLoc DL(N);
8676
8677     // The vector width should be 128 bits by the time we get here, even
8678     // if it started as 64 bits (the extract_vector handling will have
8679     // done so).
8680     assert(Vec.getValueSizeInBits() == 128 &&
8681            "unexpected vector size on extract_vector_elt!");
8682     if (Vec.getValueType() == MVT::v4i32)
8683       VecResTy = MVT::v4f32;
8684     else if (Vec.getValueType() == MVT::v2i64)
8685       VecResTy = MVT::v2f64;
8686     else
8687       llvm_unreachable("unexpected vector type!");
8688
8689     SDValue Convert =
8690         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8691     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8692   }
8693   return SDValue();
8694 }
8695
8696 // AArch64 high-vector "long" operations are formed by performing the non-high
8697 // version on an extract_subvector of each operand which gets the high half:
8698 //
8699 //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8700 //
8701 // However, there are cases which don't have an extract_high explicitly, but
8702 // have another operation that can be made compatible with one for free. For
8703 // example:
8704 //
8705 //  (dupv64 scalar) --> (extract_high (dup128 scalar))
8706 //
8707 // This routine does the actual conversion of such DUPs, once outer routines
8708 // have determined that everything else is in order.
8709 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8710 // similarly here.
8711 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8712   switch (N.getOpcode()) {
8713   case AArch64ISD::DUP:
8714   case AArch64ISD::DUPLANE8:
8715   case AArch64ISD::DUPLANE16:
8716   case AArch64ISD::DUPLANE32:
8717   case AArch64ISD::DUPLANE64:
8718   case AArch64ISD::MOVI:
8719   case AArch64ISD::MOVIshift:
8720   case AArch64ISD::MOVIedit:
8721   case AArch64ISD::MOVImsl:
8722   case AArch64ISD::MVNIshift:
8723   case AArch64ISD::MVNImsl:
8724     break;
8725   default:
8726     // FMOV could be supported, but isn't very useful, as it would only occur
8727     // if you passed a bitcast' floating point immediate to an eligible long
8728     // integer op (addl, smull, ...).
8729     return SDValue();
8730   }
8731
8732   MVT NarrowTy = N.getSimpleValueType();
8733   if (!NarrowTy.is64BitVector())
8734     return SDValue();
8735
8736   MVT ElementTy = NarrowTy.getVectorElementType();
8737   unsigned NumElems = NarrowTy.getVectorNumElements();
8738   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8739
8740   SDLoc dl(N);
8741   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8742                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8743                      DAG.getConstant(NumElems, dl, MVT::i64));
8744 }
8745
8746 static bool isEssentiallyExtractSubvector(SDValue N) {
8747   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8748     return true;
8749
8750   return N.getOpcode() == ISD::BITCAST &&
8751          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8752 }
8753
8754 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8755 struct GenericSetCCInfo {
8756   const SDValue *Opnd0;
8757   const SDValue *Opnd1;
8758   ISD::CondCode CC;
8759 };
8760
8761 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8762 struct AArch64SetCCInfo {
8763   const SDValue *Cmp;
8764   AArch64CC::CondCode CC;
8765 };
8766
8767 /// \brief Helper structure to keep track of SetCC information.
8768 union SetCCInfo {
8769   GenericSetCCInfo Generic;
8770   AArch64SetCCInfo AArch64;
8771 };
8772
8773 /// \brief Helper structure to be able to read SetCC information.  If set to
8774 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8775 /// GenericSetCCInfo.
8776 struct SetCCInfoAndKind {
8777   SetCCInfo Info;
8778   bool IsAArch64;
8779 };
8780
8781 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8782 /// an
8783 /// AArch64 lowered one.
8784 /// \p SetCCInfo is filled accordingly.
8785 /// \post SetCCInfo is meanginfull only when this function returns true.
8786 /// \return True when Op is a kind of SET_CC operation.
8787 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8788   // If this is a setcc, this is straight forward.
8789   if (Op.getOpcode() == ISD::SETCC) {
8790     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8791     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8792     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8793     SetCCInfo.IsAArch64 = false;
8794     return true;
8795   }
8796   // Otherwise, check if this is a matching csel instruction.
8797   // In other words:
8798   // - csel 1, 0, cc
8799   // - csel 0, 1, !cc
8800   if (Op.getOpcode() != AArch64ISD::CSEL)
8801     return false;
8802   // Set the information about the operands.
8803   // TODO: we want the operands of the Cmp not the csel
8804   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8805   SetCCInfo.IsAArch64 = true;
8806   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8807       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8808
8809   // Check that the operands matches the constraints:
8810   // (1) Both operands must be constants.
8811   // (2) One must be 1 and the other must be 0.
8812   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8813   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8814
8815   // Check (1).
8816   if (!TValue || !FValue)
8817     return false;
8818
8819   // Check (2).
8820   if (!TValue->isOne()) {
8821     // Update the comparison when we are interested in !cc.
8822     std::swap(TValue, FValue);
8823     SetCCInfo.Info.AArch64.CC =
8824         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8825   }
8826   return TValue->isOne() && FValue->isNullValue();
8827 }
8828
8829 // Returns true if Op is setcc or zext of setcc.
8830 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8831   if (isSetCC(Op, Info))
8832     return true;
8833   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8834     isSetCC(Op->getOperand(0), Info));
8835 }
8836
8837 // The folding we want to perform is:
8838 // (add x, [zext] (setcc cc ...) )
8839 //   -->
8840 // (csel x, (add x, 1), !cc ...)
8841 //
8842 // The latter will get matched to a CSINC instruction.
8843 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8844   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8845   SDValue LHS = Op->getOperand(0);
8846   SDValue RHS = Op->getOperand(1);
8847   SetCCInfoAndKind InfoAndKind;
8848
8849   // If neither operand is a SET_CC, give up.
8850   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8851     std::swap(LHS, RHS);
8852     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8853       return SDValue();
8854   }
8855
8856   // FIXME: This could be generatized to work for FP comparisons.
8857   EVT CmpVT = InfoAndKind.IsAArch64
8858                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8859                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
8860   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8861     return SDValue();
8862
8863   SDValue CCVal;
8864   SDValue Cmp;
8865   SDLoc dl(Op);
8866   if (InfoAndKind.IsAArch64) {
8867     CCVal = DAG.getConstant(
8868         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8869         MVT::i32);
8870     Cmp = *InfoAndKind.Info.AArch64.Cmp;
8871   } else
8872     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8873                       *InfoAndKind.Info.Generic.Opnd1,
8874                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8875                       CCVal, DAG, dl);
8876
8877   EVT VT = Op->getValueType(0);
8878   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8879   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8880 }
8881
8882 // The basic add/sub long vector instructions have variants with "2" on the end
8883 // which act on the high-half of their inputs. They are normally matched by
8884 // patterns like:
8885 //
8886 // (add (zeroext (extract_high LHS)),
8887 //      (zeroext (extract_high RHS)))
8888 // -> uaddl2 vD, vN, vM
8889 //
8890 // However, if one of the extracts is something like a duplicate, this
8891 // instruction can still be used profitably. This function puts the DAG into a
8892 // more appropriate form for those patterns to trigger.
8893 static SDValue performAddSubLongCombine(SDNode *N,
8894                                         TargetLowering::DAGCombinerInfo &DCI,
8895                                         SelectionDAG &DAG) {
8896   if (DCI.isBeforeLegalizeOps())
8897     return SDValue();
8898
8899   MVT VT = N->getSimpleValueType(0);
8900   if (!VT.is128BitVector()) {
8901     if (N->getOpcode() == ISD::ADD)
8902       return performSetccAddFolding(N, DAG);
8903     return SDValue();
8904   }
8905
8906   // Make sure both branches are extended in the same way.
8907   SDValue LHS = N->getOperand(0);
8908   SDValue RHS = N->getOperand(1);
8909   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8910        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8911       LHS.getOpcode() != RHS.getOpcode())
8912     return SDValue();
8913
8914   unsigned ExtType = LHS.getOpcode();
8915
8916   // It's not worth doing if at least one of the inputs isn't already an
8917   // extract, but we don't know which it'll be so we have to try both.
8918   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8919     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8920     if (!RHS.getNode())
8921       return SDValue();
8922
8923     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8924   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8925     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8926     if (!LHS.getNode())
8927       return SDValue();
8928
8929     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8930   }
8931
8932   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8933 }
8934
8935 // Massage DAGs which we can use the high-half "long" operations on into
8936 // something isel will recognize better. E.g.
8937 //
8938 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8939 //   (aarch64_neon_umull (extract_high (v2i64 vec)))
8940 //                     (extract_high (v2i64 (dup128 scalar)))))
8941 //
8942 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
8943                                        TargetLowering::DAGCombinerInfo &DCI,
8944                                        SelectionDAG &DAG) {
8945   if (DCI.isBeforeLegalizeOps())
8946     return SDValue();
8947
8948   SDValue LHS = N->getOperand(1);
8949   SDValue RHS = N->getOperand(2);
8950   assert(LHS.getValueType().is64BitVector() &&
8951          RHS.getValueType().is64BitVector() &&
8952          "unexpected shape for long operation");
8953
8954   // Either node could be a DUP, but it's not worth doing both of them (you'd
8955   // just as well use the non-high version) so look for a corresponding extract
8956   // operation on the other "wing".
8957   if (isEssentiallyExtractSubvector(LHS)) {
8958     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8959     if (!RHS.getNode())
8960       return SDValue();
8961   } else if (isEssentiallyExtractSubvector(RHS)) {
8962     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8963     if (!LHS.getNode())
8964       return SDValue();
8965   }
8966
8967   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8968                      N->getOperand(0), LHS, RHS);
8969 }
8970
8971 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8972   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8973   unsigned ElemBits = ElemTy.getSizeInBits();
8974
8975   int64_t ShiftAmount;
8976   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8977     APInt SplatValue, SplatUndef;
8978     unsigned SplatBitSize;
8979     bool HasAnyUndefs;
8980     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8981                               HasAnyUndefs, ElemBits) ||
8982         SplatBitSize != ElemBits)
8983       return SDValue();
8984
8985     ShiftAmount = SplatValue.getSExtValue();
8986   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8987     ShiftAmount = CVN->getSExtValue();
8988   } else
8989     return SDValue();
8990
8991   unsigned Opcode;
8992   bool IsRightShift;
8993   switch (IID) {
8994   default:
8995     llvm_unreachable("Unknown shift intrinsic");
8996   case Intrinsic::aarch64_neon_sqshl:
8997     Opcode = AArch64ISD::SQSHL_I;
8998     IsRightShift = false;
8999     break;
9000   case Intrinsic::aarch64_neon_uqshl:
9001     Opcode = AArch64ISD::UQSHL_I;
9002     IsRightShift = false;
9003     break;
9004   case Intrinsic::aarch64_neon_srshl:
9005     Opcode = AArch64ISD::SRSHR_I;
9006     IsRightShift = true;
9007     break;
9008   case Intrinsic::aarch64_neon_urshl:
9009     Opcode = AArch64ISD::URSHR_I;
9010     IsRightShift = true;
9011     break;
9012   case Intrinsic::aarch64_neon_sqshlu:
9013     Opcode = AArch64ISD::SQSHLU_I;
9014     IsRightShift = false;
9015     break;
9016   }
9017
9018   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
9019     SDLoc dl(N);
9020     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9021                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
9022   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
9023     SDLoc dl(N);
9024     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9025                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
9026   }
9027
9028   return SDValue();
9029 }
9030
9031 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
9032 // the intrinsics must be legal and take an i32, this means there's almost
9033 // certainly going to be a zext in the DAG which we can eliminate.
9034 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
9035   SDValue AndN = N->getOperand(2);
9036   if (AndN.getOpcode() != ISD::AND)
9037     return SDValue();
9038
9039   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
9040   if (!CMask || CMask->getZExtValue() != Mask)
9041     return SDValue();
9042
9043   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
9044                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
9045 }
9046
9047 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
9048                                            SelectionDAG &DAG) {
9049   SDLoc dl(N);
9050   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
9051                      DAG.getNode(Opc, dl,
9052                                  N->getOperand(1).getSimpleValueType(),
9053                                  N->getOperand(1)),
9054                      DAG.getConstant(0, dl, MVT::i64));
9055 }
9056
9057 static SDValue performIntrinsicCombine(SDNode *N,
9058                                        TargetLowering::DAGCombinerInfo &DCI,
9059                                        const AArch64Subtarget *Subtarget) {
9060   SelectionDAG &DAG = DCI.DAG;
9061   unsigned IID = getIntrinsicID(N);
9062   switch (IID) {
9063   default:
9064     break;
9065   case Intrinsic::aarch64_neon_vcvtfxs2fp:
9066   case Intrinsic::aarch64_neon_vcvtfxu2fp:
9067     return tryCombineFixedPointConvert(N, DCI, DAG);
9068   case Intrinsic::aarch64_neon_saddv:
9069     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
9070   case Intrinsic::aarch64_neon_uaddv:
9071     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
9072   case Intrinsic::aarch64_neon_sminv:
9073     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
9074   case Intrinsic::aarch64_neon_uminv:
9075     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
9076   case Intrinsic::aarch64_neon_smaxv:
9077     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
9078   case Intrinsic::aarch64_neon_umaxv:
9079     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
9080   case Intrinsic::aarch64_neon_fmax:
9081     return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
9082                        N->getOperand(1), N->getOperand(2));
9083   case Intrinsic::aarch64_neon_fmin:
9084     return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
9085                        N->getOperand(1), N->getOperand(2));
9086   case Intrinsic::aarch64_neon_fmaxnm:
9087     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
9088                        N->getOperand(1), N->getOperand(2));
9089   case Intrinsic::aarch64_neon_fminnm:
9090     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
9091                        N->getOperand(1), N->getOperand(2));
9092   case Intrinsic::aarch64_neon_smull:
9093   case Intrinsic::aarch64_neon_umull:
9094   case Intrinsic::aarch64_neon_pmull:
9095   case Intrinsic::aarch64_neon_sqdmull:
9096     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
9097   case Intrinsic::aarch64_neon_sqshl:
9098   case Intrinsic::aarch64_neon_uqshl:
9099   case Intrinsic::aarch64_neon_sqshlu:
9100   case Intrinsic::aarch64_neon_srshl:
9101   case Intrinsic::aarch64_neon_urshl:
9102     return tryCombineShiftImm(IID, N, DAG);
9103   case Intrinsic::aarch64_crc32b:
9104   case Intrinsic::aarch64_crc32cb:
9105     return tryCombineCRC32(0xff, N, DAG);
9106   case Intrinsic::aarch64_crc32h:
9107   case Intrinsic::aarch64_crc32ch:
9108     return tryCombineCRC32(0xffff, N, DAG);
9109   }
9110   return SDValue();
9111 }
9112
9113 static SDValue performExtendCombine(SDNode *N,
9114                                     TargetLowering::DAGCombinerInfo &DCI,
9115                                     SelectionDAG &DAG) {
9116   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
9117   // we can convert that DUP into another extract_high (of a bigger DUP), which
9118   // helps the backend to decide that an sabdl2 would be useful, saving a real
9119   // extract_high operation.
9120   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
9121       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
9122     SDNode *ABDNode = N->getOperand(0).getNode();
9123     unsigned IID = getIntrinsicID(ABDNode);
9124     if (IID == Intrinsic::aarch64_neon_sabd ||
9125         IID == Intrinsic::aarch64_neon_uabd) {
9126       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
9127       if (!NewABD.getNode())
9128         return SDValue();
9129
9130       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
9131                          NewABD);
9132     }
9133   }
9134
9135   // This is effectively a custom type legalization for AArch64.
9136   //
9137   // Type legalization will split an extend of a small, legal, type to a larger
9138   // illegal type by first splitting the destination type, often creating
9139   // illegal source types, which then get legalized in isel-confusing ways,
9140   // leading to really terrible codegen. E.g.,
9141   //   %result = v8i32 sext v8i8 %value
9142   // becomes
9143   //   %losrc = extract_subreg %value, ...
9144   //   %hisrc = extract_subreg %value, ...
9145   //   %lo = v4i32 sext v4i8 %losrc
9146   //   %hi = v4i32 sext v4i8 %hisrc
9147   // Things go rapidly downhill from there.
9148   //
9149   // For AArch64, the [sz]ext vector instructions can only go up one element
9150   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
9151   // take two instructions.
9152   //
9153   // This implies that the most efficient way to do the extend from v8i8
9154   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
9155   // the normal splitting to happen for the v8i16->v8i32.
9156
9157   // This is pre-legalization to catch some cases where the default
9158   // type legalization will create ill-tempered code.
9159   if (!DCI.isBeforeLegalizeOps())
9160     return SDValue();
9161
9162   // We're only interested in cleaning things up for non-legal vector types
9163   // here. If both the source and destination are legal, things will just
9164   // work naturally without any fiddling.
9165   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9166   EVT ResVT = N->getValueType(0);
9167   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
9168     return SDValue();
9169   // If the vector type isn't a simple VT, it's beyond the scope of what
9170   // we're  worried about here. Let legalization do its thing and hope for
9171   // the best.
9172   SDValue Src = N->getOperand(0);
9173   EVT SrcVT = Src->getValueType(0);
9174   if (!ResVT.isSimple() || !SrcVT.isSimple())
9175     return SDValue();
9176
9177   // If the source VT is a 64-bit vector, we can play games and get the
9178   // better results we want.
9179   if (SrcVT.getSizeInBits() != 64)
9180     return SDValue();
9181
9182   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
9183   unsigned ElementCount = SrcVT.getVectorNumElements();
9184   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
9185   SDLoc DL(N);
9186   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
9187
9188   // Now split the rest of the operation into two halves, each with a 64
9189   // bit source.
9190   EVT LoVT, HiVT;
9191   SDValue Lo, Hi;
9192   unsigned NumElements = ResVT.getVectorNumElements();
9193   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
9194   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
9195                                  ResVT.getVectorElementType(), NumElements / 2);
9196
9197   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
9198                                LoVT.getVectorNumElements());
9199   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
9200                    DAG.getConstant(0, DL, MVT::i64));
9201   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
9202                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
9203   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
9204   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
9205
9206   // Now combine the parts back together so we still have a single result
9207   // like the combiner expects.
9208   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
9209 }
9210
9211 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
9212                                SDValue SplatVal, unsigned NumVecElts) {
9213   unsigned OrigAlignment = St.getAlignment();
9214   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
9215
9216   // Create scalar stores. This is at least as good as the code sequence for a
9217   // split unaligned store which is a dup.s, ext.b, and two stores.
9218   // Most of the time the three stores should be replaced by store pair
9219   // instructions (stp).
9220   SDLoc DL(&St);
9221   SDValue BasePtr = St.getBasePtr();
9222   uint64_t BaseOffset = 0;
9223
9224   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
9225   SDValue NewST1 =
9226       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
9227                    OrigAlignment, St.getMemOperand()->getFlags());
9228
9229   // As this in ISel, we will not merge this add which may degrade results.
9230   if (BasePtr->getOpcode() == ISD::ADD &&
9231       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
9232     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
9233     BasePtr = BasePtr->getOperand(0);
9234   }
9235
9236   unsigned Offset = EltOffset;
9237   while (--NumVecElts) {
9238     unsigned Alignment = MinAlign(OrigAlignment, Offset);
9239     SDValue OffsetPtr =
9240         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9241                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
9242     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
9243                           PtrInfo.getWithOffset(Offset), Alignment,
9244                           St.getMemOperand()->getFlags());
9245     Offset += EltOffset;
9246   }
9247   return NewST1;
9248 }
9249
9250 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
9251 /// load store optimizer pass will merge them to store pair stores.  This should
9252 /// be better than a movi to create the vector zero followed by a vector store
9253 /// if the zero constant is not re-used, since one instructions and one register
9254 /// live range will be removed.
9255 ///
9256 /// For example, the final generated code should be:
9257 ///
9258 ///   stp xzr, xzr, [x0]
9259 ///
9260 /// instead of:
9261 ///
9262 ///   movi v0.2d, #0
9263 ///   str q0, [x0]
9264 ///
9265 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9266   SDValue StVal = St.getValue();
9267   EVT VT = StVal.getValueType();
9268
9269   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
9270   // 2, 3 or 4 i32 elements.
9271   int NumVecElts = VT.getVectorNumElements();
9272   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
9273          VT.getVectorElementType().getSizeInBits() == 64) ||
9274         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
9275          VT.getVectorElementType().getSizeInBits() == 32)))
9276     return SDValue();
9277
9278   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
9279     return SDValue();
9280
9281   // If the zero constant has more than one use then the vector store could be
9282   // better since the constant mov will be amortized and stp q instructions
9283   // should be able to be formed.
9284   if (!StVal.hasOneUse())
9285     return SDValue();
9286
9287   // If the immediate offset of the address operand is too large for the stp
9288   // instruction, then bail out.
9289   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
9290     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
9291     if (Offset < -512 || Offset > 504)
9292       return SDValue();
9293   }
9294
9295   for (int I = 0; I < NumVecElts; ++I) {
9296     SDValue EltVal = StVal.getOperand(I);
9297     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
9298       return SDValue();
9299   }
9300
9301   // Use WZR/XZR here to prevent DAGCombiner::MergeConsecutiveStores from
9302   // undoing this transformation.
9303   SDValue SplatVal = VT.getVectorElementType().getSizeInBits() == 32
9304                          ? DAG.getRegister(AArch64::WZR, MVT::i32)
9305                          : DAG.getRegister(AArch64::XZR, MVT::i64);
9306   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
9307 }
9308
9309 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
9310 /// value. The load store optimizer pass will merge them to store pair stores.
9311 /// This has better performance than a splat of the scalar followed by a split
9312 /// vector store. Even if the stores are not merged it is four stores vs a dup,
9313 /// followed by an ext.b and two stores.
9314 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9315   SDValue StVal = St.getValue();
9316   EVT VT = StVal.getValueType();
9317
9318   // Don't replace floating point stores, they possibly won't be transformed to
9319   // stp because of the store pair suppress pass.
9320   if (VT.isFloatingPoint())
9321     return SDValue();
9322
9323   // We can express a splat as store pair(s) for 2 or 4 elements.
9324   unsigned NumVecElts = VT.getVectorNumElements();
9325   if (NumVecElts != 4 && NumVecElts != 2)
9326     return SDValue();
9327
9328   // Check that this is a splat.
9329   // Make sure that each of the relevant vector element locations are inserted
9330   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
9331   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
9332   SDValue SplatVal;
9333   for (unsigned I = 0; I < NumVecElts; ++I) {
9334     // Check for insert vector elements.
9335     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
9336       return SDValue();
9337
9338     // Check that same value is inserted at each vector element.
9339     if (I == 0)
9340       SplatVal = StVal.getOperand(1);
9341     else if (StVal.getOperand(1) != SplatVal)
9342       return SDValue();
9343
9344     // Check insert element index.
9345     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
9346     if (!CIndex)
9347       return SDValue();
9348     uint64_t IndexVal = CIndex->getZExtValue();
9349     if (IndexVal >= NumVecElts)
9350       return SDValue();
9351     IndexNotInserted.reset(IndexVal);
9352
9353     StVal = StVal.getOperand(0);
9354   }
9355   // Check that all vector element locations were inserted to.
9356   if (IndexNotInserted.any())
9357       return SDValue();
9358
9359   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
9360 }
9361
9362 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9363                            SelectionDAG &DAG,
9364                            const AArch64Subtarget *Subtarget) {
9365   if (!DCI.isBeforeLegalize())
9366     return SDValue();
9367
9368   StoreSDNode *S = cast<StoreSDNode>(N);
9369   if (S->isVolatile())
9370     return SDValue();
9371
9372   SDValue StVal = S->getValue();
9373   EVT VT = StVal.getValueType();
9374   if (!VT.isVector())
9375     return SDValue();
9376
9377   // If we get a splat of zeros, convert this vector store to a store of
9378   // scalars. They will be merged into store pairs of xzr thereby removing one
9379   // instruction and one register.
9380   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
9381     return ReplacedZeroSplat;
9382
9383   // FIXME: The logic for deciding if an unaligned store should be split should
9384   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
9385   // a call to that function here.
9386
9387   if (!Subtarget->isMisaligned128StoreSlow())
9388     return SDValue();
9389
9390   // Don't split at -Oz.
9391   if (DAG.getMachineFunction().getFunction()->optForMinSize())
9392     return SDValue();
9393
9394   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
9395   // those up regresses performance on micro-benchmarks and olden/bh.
9396   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
9397     return SDValue();
9398
9399   // Split unaligned 16B stores. They are terrible for performance.
9400   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
9401   // extensions can use this to mark that it does not want splitting to happen
9402   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
9403   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
9404   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
9405       S->getAlignment() <= 2)
9406     return SDValue();
9407
9408   // If we get a splat of a scalar convert this vector store to a store of
9409   // scalars. They will be merged into store pairs thereby removing two
9410   // instructions.
9411   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
9412     return ReplacedSplat;
9413
9414   SDLoc DL(S);
9415   unsigned NumElts = VT.getVectorNumElements() / 2;
9416   // Split VT into two.
9417   EVT HalfVT =
9418       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
9419   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9420                                    DAG.getConstant(0, DL, MVT::i64));
9421   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9422                                    DAG.getConstant(NumElts, DL, MVT::i64));
9423   SDValue BasePtr = S->getBasePtr();
9424   SDValue NewST1 =
9425       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
9426                    S->getAlignment(), S->getMemOperand()->getFlags());
9427   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9428                                   DAG.getConstant(8, DL, MVT::i64));
9429   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
9430                       S->getPointerInfo(), S->getAlignment(),
9431                       S->getMemOperand()->getFlags());
9432 }
9433
9434 /// Target-specific DAG combine function for post-increment LD1 (lane) and
9435 /// post-increment LD1R.
9436 static SDValue performPostLD1Combine(SDNode *N,
9437                                      TargetLowering::DAGCombinerInfo &DCI,
9438                                      bool IsLaneOp) {
9439   if (DCI.isBeforeLegalizeOps())
9440     return SDValue();
9441
9442   SelectionDAG &DAG = DCI.DAG;
9443   EVT VT = N->getValueType(0);
9444
9445   unsigned LoadIdx = IsLaneOp ? 1 : 0;
9446   SDNode *LD = N->getOperand(LoadIdx).getNode();
9447   // If it is not LOAD, can not do such combine.
9448   if (LD->getOpcode() != ISD::LOAD)
9449     return SDValue();
9450
9451   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
9452   EVT MemVT = LoadSDN->getMemoryVT();
9453   // Check if memory operand is the same type as the vector element.
9454   if (MemVT != VT.getVectorElementType())
9455     return SDValue();
9456
9457   // Check if there are other uses. If so, do not combine as it will introduce
9458   // an extra load.
9459   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
9460        ++UI) {
9461     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
9462       continue;
9463     if (*UI != N)
9464       return SDValue();
9465   }
9466
9467   SDValue Addr = LD->getOperand(1);
9468   SDValue Vector = N->getOperand(0);
9469   // Search for a use of the address operand that is an increment.
9470   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
9471        Addr.getNode()->use_end(); UI != UE; ++UI) {
9472     SDNode *User = *UI;
9473     if (User->getOpcode() != ISD::ADD
9474         || UI.getUse().getResNo() != Addr.getResNo())
9475       continue;
9476
9477     // Check that the add is independent of the load.  Otherwise, folding it
9478     // would create a cycle.
9479     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
9480       continue;
9481     // Also check that add is not used in the vector operand.  This would also
9482     // create a cycle.
9483     if (User->isPredecessorOf(Vector.getNode()))
9484       continue;
9485
9486     // If the increment is a constant, it must match the memory ref size.
9487     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9488     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9489       uint32_t IncVal = CInc->getZExtValue();
9490       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
9491       if (IncVal != NumBytes)
9492         continue;
9493       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9494     }
9495
9496     // Finally, check that the vector doesn't depend on the load.
9497     // Again, this would create a cycle.
9498     // The load depending on the vector is fine, as that's the case for the
9499     // LD1*post we'll eventually generate anyway.
9500     if (LoadSDN->isPredecessorOf(Vector.getNode()))
9501       continue;
9502
9503     SmallVector<SDValue, 8> Ops;
9504     Ops.push_back(LD->getOperand(0));  // Chain
9505     if (IsLaneOp) {
9506       Ops.push_back(Vector);           // The vector to be inserted
9507       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
9508     }
9509     Ops.push_back(Addr);
9510     Ops.push_back(Inc);
9511
9512     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
9513     SDVTList SDTys = DAG.getVTList(Tys);
9514     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
9515     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
9516                                            MemVT,
9517                                            LoadSDN->getMemOperand());
9518
9519     // Update the uses.
9520     SDValue NewResults[] = {
9521         SDValue(LD, 0),            // The result of load
9522         SDValue(UpdN.getNode(), 2) // Chain
9523     };
9524     DCI.CombineTo(LD, NewResults);
9525     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
9526     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
9527
9528     break;
9529   }
9530   return SDValue();
9531 }
9532
9533 /// Simplify \Addr given that the top byte of it is ignored by HW during
9534 /// address translation.
9535 static bool performTBISimplification(SDValue Addr,
9536                                      TargetLowering::DAGCombinerInfo &DCI,
9537                                      SelectionDAG &DAG) {
9538   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
9539   KnownBits Known;
9540   TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
9541                                         DCI.isBeforeLegalizeOps());
9542   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9543   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
9544     DCI.CommitTargetLoweringOpt(TLO);
9545     return true;
9546   }
9547   return false;
9548 }
9549
9550 static SDValue performSTORECombine(SDNode *N,
9551                                    TargetLowering::DAGCombinerInfo &DCI,
9552                                    SelectionDAG &DAG,
9553                                    const AArch64Subtarget *Subtarget) {
9554   if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
9555     return Split;
9556
9557   if (Subtarget->supportsAddressTopByteIgnored() &&
9558       performTBISimplification(N->getOperand(2), DCI, DAG))
9559     return SDValue(N, 0);
9560
9561   return SDValue();
9562 }
9563
9564
9565 /// Target-specific DAG combine function for NEON load/store intrinsics
9566 /// to merge base address updates.
9567 static SDValue performNEONPostLDSTCombine(SDNode *N,
9568                                           TargetLowering::DAGCombinerInfo &DCI,
9569                                           SelectionDAG &DAG) {
9570   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9571     return SDValue();
9572
9573   unsigned AddrOpIdx = N->getNumOperands() - 1;
9574   SDValue Addr = N->getOperand(AddrOpIdx);
9575
9576   // Search for a use of the address operand that is an increment.
9577   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9578        UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9579     SDNode *User = *UI;
9580     if (User->getOpcode() != ISD::ADD ||
9581         UI.getUse().getResNo() != Addr.getResNo())
9582       continue;
9583
9584     // Check that the add is independent of the load/store.  Otherwise, folding
9585     // it would create a cycle.
9586     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9587       continue;
9588
9589     // Find the new opcode for the updating load/store.
9590     bool IsStore = false;
9591     bool IsLaneOp = false;
9592     bool IsDupOp = false;
9593     unsigned NewOpc = 0;
9594     unsigned NumVecs = 0;
9595     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9596     switch (IntNo) {
9597     default: llvm_unreachable("unexpected intrinsic for Neon base update");
9598     case Intrinsic::aarch64_neon_ld2:       NewOpc = AArch64ISD::LD2post;
9599       NumVecs = 2; break;
9600     case Intrinsic::aarch64_neon_ld3:       NewOpc = AArch64ISD::LD3post;
9601       NumVecs = 3; break;
9602     case Intrinsic::aarch64_neon_ld4:       NewOpc = AArch64ISD::LD4post;
9603       NumVecs = 4; break;
9604     case Intrinsic::aarch64_neon_st2:       NewOpc = AArch64ISD::ST2post;
9605       NumVecs = 2; IsStore = true; break;
9606     case Intrinsic::aarch64_neon_st3:       NewOpc = AArch64ISD::ST3post;
9607       NumVecs = 3; IsStore = true; break;
9608     case Intrinsic::aarch64_neon_st4:       NewOpc = AArch64ISD::ST4post;
9609       NumVecs = 4; IsStore = true; break;
9610     case Intrinsic::aarch64_neon_ld1x2:     NewOpc = AArch64ISD::LD1x2post;
9611       NumVecs = 2; break;
9612     case Intrinsic::aarch64_neon_ld1x3:     NewOpc = AArch64ISD::LD1x3post;
9613       NumVecs = 3; break;
9614     case Intrinsic::aarch64_neon_ld1x4:     NewOpc = AArch64ISD::LD1x4post;
9615       NumVecs = 4; break;
9616     case Intrinsic::aarch64_neon_st1x2:     NewOpc = AArch64ISD::ST1x2post;
9617       NumVecs = 2; IsStore = true; break;
9618     case Intrinsic::aarch64_neon_st1x3:     NewOpc = AArch64ISD::ST1x3post;
9619       NumVecs = 3; IsStore = true; break;
9620     case Intrinsic::aarch64_neon_st1x4:     NewOpc = AArch64ISD::ST1x4post;
9621       NumVecs = 4; IsStore = true; break;
9622     case Intrinsic::aarch64_neon_ld2r:      NewOpc = AArch64ISD::LD2DUPpost;
9623       NumVecs = 2; IsDupOp = true; break;
9624     case Intrinsic::aarch64_neon_ld3r:      NewOpc = AArch64ISD::LD3DUPpost;
9625       NumVecs = 3; IsDupOp = true; break;
9626     case Intrinsic::aarch64_neon_ld4r:      NewOpc = AArch64ISD::LD4DUPpost;
9627       NumVecs = 4; IsDupOp = true; break;
9628     case Intrinsic::aarch64_neon_ld2lane:   NewOpc = AArch64ISD::LD2LANEpost;
9629       NumVecs = 2; IsLaneOp = true; break;
9630     case Intrinsic::aarch64_neon_ld3lane:   NewOpc = AArch64ISD::LD3LANEpost;
9631       NumVecs = 3; IsLaneOp = true; break;
9632     case Intrinsic::aarch64_neon_ld4lane:   NewOpc = AArch64ISD::LD4LANEpost;
9633       NumVecs = 4; IsLaneOp = true; break;
9634     case Intrinsic::aarch64_neon_st2lane:   NewOpc = AArch64ISD::ST2LANEpost;
9635       NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9636     case Intrinsic::aarch64_neon_st3lane:   NewOpc = AArch64ISD::ST3LANEpost;
9637       NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9638     case Intrinsic::aarch64_neon_st4lane:   NewOpc = AArch64ISD::ST4LANEpost;
9639       NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9640     }
9641
9642     EVT VecTy;
9643     if (IsStore)
9644       VecTy = N->getOperand(2).getValueType();
9645     else
9646       VecTy = N->getValueType(0);
9647
9648     // If the increment is a constant, it must match the memory ref size.
9649     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9650     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9651       uint32_t IncVal = CInc->getZExtValue();
9652       unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9653       if (IsLaneOp || IsDupOp)
9654         NumBytes /= VecTy.getVectorNumElements();
9655       if (IncVal != NumBytes)
9656         continue;
9657       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9658     }
9659     SmallVector<SDValue, 8> Ops;
9660     Ops.push_back(N->getOperand(0)); // Incoming chain
9661     // Load lane and store have vector list as input.
9662     if (IsLaneOp || IsStore)
9663       for (unsigned i = 2; i < AddrOpIdx; ++i)
9664         Ops.push_back(N->getOperand(i));
9665     Ops.push_back(Addr); // Base register
9666     Ops.push_back(Inc);
9667
9668     // Return Types.
9669     EVT Tys[6];
9670     unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9671     unsigned n;
9672     for (n = 0; n < NumResultVecs; ++n)
9673       Tys[n] = VecTy;
9674     Tys[n++] = MVT::i64;  // Type of write back register
9675     Tys[n] = MVT::Other;  // Type of the chain
9676     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9677
9678     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9679     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9680                                            MemInt->getMemoryVT(),
9681                                            MemInt->getMemOperand());
9682
9683     // Update the uses.
9684     std::vector<SDValue> NewResults;
9685     for (unsigned i = 0; i < NumResultVecs; ++i) {
9686       NewResults.push_back(SDValue(UpdN.getNode(), i));
9687     }
9688     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9689     DCI.CombineTo(N, NewResults);
9690     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9691
9692     break;
9693   }
9694   return SDValue();
9695 }
9696
9697 // Checks to see if the value is the prescribed width and returns information
9698 // about its extension mode.
9699 static
9700 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9701   ExtType = ISD::NON_EXTLOAD;
9702   switch(V.getNode()->getOpcode()) {
9703   default:
9704     return false;
9705   case ISD::LOAD: {
9706     LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9707     if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9708        || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9709       ExtType = LoadNode->getExtensionType();
9710       return true;
9711     }
9712     return false;
9713   }
9714   case ISD::AssertSext: {
9715     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9716     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9717        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9718       ExtType = ISD::SEXTLOAD;
9719       return true;
9720     }
9721     return false;
9722   }
9723   case ISD::AssertZext: {
9724     VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9725     if ((TypeNode->getVT() == MVT::i8 && width == 8)
9726        || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9727       ExtType = ISD::ZEXTLOAD;
9728       return true;
9729     }
9730     return false;
9731   }
9732   case ISD::Constant:
9733   case ISD::TargetConstant: {
9734     return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9735            1LL << (width - 1);
9736   }
9737   }
9738
9739   return true;
9740 }
9741
9742 // This function does a whole lot of voodoo to determine if the tests are
9743 // equivalent without and with a mask. Essentially what happens is that given a
9744 // DAG resembling:
9745 //
9746 //  +-------------+ +-------------+ +-------------+ +-------------+
9747 //  |    Input    | | AddConstant | | CompConstant| |     CC      |
9748 //  +-------------+ +-------------+ +-------------+ +-------------+
9749 //           |           |           |               |
9750 //           V           V           |    +----------+
9751 //          +-------------+  +----+  |    |
9752 //          |     ADD     |  |0xff|  |    |
9753 //          +-------------+  +----+  |    |
9754 //                  |           |    |    |
9755 //                  V           V    |    |
9756 //                 +-------------+   |    |
9757 //                 |     AND     |   |    |
9758 //                 +-------------+   |    |
9759 //                      |            |    |
9760 //                      +-----+      |    |
9761 //                            |      |    |
9762 //                            V      V    V
9763 //                           +-------------+
9764 //                           |     CMP     |
9765 //                           +-------------+
9766 //
9767 // The AND node may be safely removed for some combinations of inputs. In
9768 // particular we need to take into account the extension type of the Input,
9769 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9770 // width of the input (this can work for any width inputs, the above graph is
9771 // specific to 8 bits.
9772 //
9773 // The specific equations were worked out by generating output tables for each
9774 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9775 // problem was simplified by working with 4 bit inputs, which means we only
9776 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9777 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9778 // patterns present in both extensions (0,7). For every distinct set of
9779 // AddConstant and CompConstants bit patterns we can consider the masked and
9780 // unmasked versions to be equivalent if the result of this function is true for
9781 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9782 //
9783 //   sub      w8, w0, w1
9784 //   and      w10, w8, #0x0f
9785 //   cmp      w8, w2
9786 //   cset     w9, AArch64CC
9787 //   cmp      w10, w2
9788 //   cset     w11, AArch64CC
9789 //   cmp      w9, w11
9790 //   cset     w0, eq
9791 //   ret
9792 //
9793 // Since the above function shows when the outputs are equivalent it defines
9794 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9795 // would be expensive to run during compiles. The equations below were written
9796 // in a test harness that confirmed they gave equivalent outputs to the above
9797 // for all inputs function, so they can be used determine if the removal is
9798 // legal instead.
9799 //
9800 // isEquivalentMaskless() is the code for testing if the AND can be removed
9801 // factored out of the DAG recognition as the DAG can take several forms.
9802
9803 static bool isEquivalentMaskless(unsigned CC, unsigned width,
9804                                  ISD::LoadExtType ExtType, int AddConstant,
9805                                  int CompConstant) {
9806   // By being careful about our equations and only writing the in term
9807   // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9808   // make them generally applicable to all bit widths.
9809   int MaxUInt = (1 << width);
9810
9811   // For the purposes of these comparisons sign extending the type is
9812   // equivalent to zero extending the add and displacing it by half the integer
9813   // width. Provided we are careful and make sure our equations are valid over
9814   // the whole range we can just adjust the input and avoid writing equations
9815   // for sign extended inputs.
9816   if (ExtType == ISD::SEXTLOAD)
9817     AddConstant -= (1 << (width-1));
9818
9819   switch(CC) {
9820   case AArch64CC::LE:
9821   case AArch64CC::GT:
9822     if ((AddConstant == 0) ||
9823         (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9824         (AddConstant >= 0 && CompConstant < 0) ||
9825         (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9826       return true;
9827     break;
9828   case AArch64CC::LT:
9829   case AArch64CC::GE:
9830     if ((AddConstant == 0) ||
9831         (AddConstant >= 0 && CompConstant <= 0) ||
9832         (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9833       return true;
9834     break;
9835   case AArch64CC::HI:
9836   case AArch64CC::LS:
9837     if ((AddConstant >= 0 && CompConstant < 0) ||
9838        (AddConstant <= 0 && CompConstant >= -1 &&
9839         CompConstant < AddConstant + MaxUInt))
9840       return true;
9841    break;
9842   case AArch64CC::PL:
9843   case AArch64CC::MI:
9844     if ((AddConstant == 0) ||
9845         (AddConstant > 0 && CompConstant <= 0) ||
9846         (AddConstant < 0 && CompConstant <= AddConstant))
9847       return true;
9848     break;
9849   case AArch64CC::LO:
9850   case AArch64CC::HS:
9851     if ((AddConstant >= 0 && CompConstant <= 0) ||
9852         (AddConstant <= 0 && CompConstant >= 0 &&
9853          CompConstant <= AddConstant + MaxUInt))
9854       return true;
9855     break;
9856   case AArch64CC::EQ:
9857   case AArch64CC::NE:
9858     if ((AddConstant > 0 && CompConstant < 0) ||
9859         (AddConstant < 0 && CompConstant >= 0 &&
9860          CompConstant < AddConstant + MaxUInt) ||
9861         (AddConstant >= 0 && CompConstant >= 0 &&
9862          CompConstant >= AddConstant) ||
9863         (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9864       return true;
9865     break;
9866   case AArch64CC::VS:
9867   case AArch64CC::VC:
9868   case AArch64CC::AL:
9869   case AArch64CC::NV:
9870     return true;
9871   case AArch64CC::Invalid:
9872     break;
9873   }
9874
9875   return false;
9876 }
9877
9878 static
9879 SDValue performCONDCombine(SDNode *N,
9880                            TargetLowering::DAGCombinerInfo &DCI,
9881                            SelectionDAG &DAG, unsigned CCIndex,
9882                            unsigned CmpIndex) {
9883   unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9884   SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9885   unsigned CondOpcode = SubsNode->getOpcode();
9886
9887   if (CondOpcode != AArch64ISD::SUBS)
9888     return SDValue();
9889
9890   // There is a SUBS feeding this condition. Is it fed by a mask we can
9891   // use?
9892
9893   SDNode *AndNode = SubsNode->getOperand(0).getNode();
9894   unsigned MaskBits = 0;
9895
9896   if (AndNode->getOpcode() != ISD::AND)
9897     return SDValue();
9898
9899   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9900     uint32_t CNV = CN->getZExtValue();
9901     if (CNV == 255)
9902       MaskBits = 8;
9903     else if (CNV == 65535)
9904       MaskBits = 16;
9905   }
9906
9907   if (!MaskBits)
9908     return SDValue();
9909
9910   SDValue AddValue = AndNode->getOperand(0);
9911
9912   if (AddValue.getOpcode() != ISD::ADD)
9913     return SDValue();
9914
9915   // The basic dag structure is correct, grab the inputs and validate them.
9916
9917   SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9918   SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9919   SDValue SubsInputValue = SubsNode->getOperand(1);
9920
9921   // The mask is present and the provenance of all the values is a smaller type,
9922   // lets see if the mask is superfluous.
9923
9924   if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9925       !isa<ConstantSDNode>(SubsInputValue.getNode()))
9926     return SDValue();
9927
9928   ISD::LoadExtType ExtType;
9929
9930   if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9931       !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9932       !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9933     return SDValue();
9934
9935   if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9936                 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9937                 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9938     return SDValue();
9939
9940   // The AND is not necessary, remove it.
9941
9942   SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9943                                SubsNode->getValueType(1));
9944   SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9945
9946   SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9947   DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9948
9949   return SDValue(N, 0);
9950 }
9951
9952 // Optimize compare with zero and branch.
9953 static SDValue performBRCONDCombine(SDNode *N,
9954                                     TargetLowering::DAGCombinerInfo &DCI,
9955                                     SelectionDAG &DAG) {
9956   if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
9957     N = NV.getNode();
9958   SDValue Chain = N->getOperand(0);
9959   SDValue Dest = N->getOperand(1);
9960   SDValue CCVal = N->getOperand(2);
9961   SDValue Cmp = N->getOperand(3);
9962
9963   assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9964   unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9965   if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9966     return SDValue();
9967
9968   unsigned CmpOpc = Cmp.getOpcode();
9969   if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9970     return SDValue();
9971
9972   // Only attempt folding if there is only one use of the flag and no use of the
9973   // value.
9974   if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9975     return SDValue();
9976
9977   SDValue LHS = Cmp.getOperand(0);
9978   SDValue RHS = Cmp.getOperand(1);
9979
9980   assert(LHS.getValueType() == RHS.getValueType() &&
9981          "Expected the value type to be the same for both operands!");
9982   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9983     return SDValue();
9984
9985   if (isNullConstant(LHS))
9986     std::swap(LHS, RHS);
9987
9988   if (!isNullConstant(RHS))
9989     return SDValue();
9990
9991   if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9992       LHS.getOpcode() == ISD::SRL)
9993     return SDValue();
9994
9995   // Fold the compare into the branch instruction.
9996   SDValue BR;
9997   if (CC == AArch64CC::EQ)
9998     BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9999   else
10000     BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10001
10002   // Do not add new nodes to DAG combiner worklist.
10003   DCI.CombineTo(N, BR, false);
10004
10005   return SDValue();
10006 }
10007
10008 // Optimize some simple tbz/tbnz cases.  Returns the new operand and bit to test
10009 // as well as whether the test should be inverted.  This code is required to
10010 // catch these cases (as opposed to standard dag combines) because
10011 // AArch64ISD::TBZ is matched during legalization.
10012 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
10013                                  SelectionDAG &DAG) {
10014
10015   if (!Op->hasOneUse())
10016     return Op;
10017
10018   // We don't handle undef/constant-fold cases below, as they should have
10019   // already been taken care of (e.g. and of 0, test of undefined shifted bits,
10020   // etc.)
10021
10022   // (tbz (trunc x), b) -> (tbz x, b)
10023   // This case is just here to enable more of the below cases to be caught.
10024   if (Op->getOpcode() == ISD::TRUNCATE &&
10025       Bit < Op->getValueType(0).getSizeInBits()) {
10026     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10027   }
10028
10029   if (Op->getNumOperands() != 2)
10030     return Op;
10031
10032   auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
10033   if (!C)
10034     return Op;
10035
10036   switch (Op->getOpcode()) {
10037   default:
10038     return Op;
10039
10040   // (tbz (and x, m), b) -> (tbz x, b)
10041   case ISD::AND:
10042     if ((C->getZExtValue() >> Bit) & 1)
10043       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10044     return Op;
10045
10046   // (tbz (shl x, c), b) -> (tbz x, b-c)
10047   case ISD::SHL:
10048     if (C->getZExtValue() <= Bit &&
10049         (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10050       Bit = Bit - C->getZExtValue();
10051       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10052     }
10053     return Op;
10054
10055   // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
10056   case ISD::SRA:
10057     Bit = Bit + C->getZExtValue();
10058     if (Bit >= Op->getValueType(0).getSizeInBits())
10059       Bit = Op->getValueType(0).getSizeInBits() - 1;
10060     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10061
10062   // (tbz (srl x, c), b) -> (tbz x, b+c)
10063   case ISD::SRL:
10064     if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10065       Bit = Bit + C->getZExtValue();
10066       return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10067     }
10068     return Op;
10069
10070   // (tbz (xor x, -1), b) -> (tbnz x, b)
10071   case ISD::XOR:
10072     if ((C->getZExtValue() >> Bit) & 1)
10073       Invert = !Invert;
10074     return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10075   }
10076 }
10077
10078 // Optimize test single bit zero/non-zero and branch.
10079 static SDValue performTBZCombine(SDNode *N,
10080                                  TargetLowering::DAGCombinerInfo &DCI,
10081                                  SelectionDAG &DAG) {
10082   unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10083   bool Invert = false;
10084   SDValue TestSrc = N->getOperand(1);
10085   SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10086
10087   if (TestSrc == NewTestSrc)
10088     return SDValue();
10089
10090   unsigned NewOpc = N->getOpcode();
10091   if (Invert) {
10092     if (NewOpc == AArch64ISD::TBZ)
10093       NewOpc = AArch64ISD::TBNZ;
10094     else {
10095       assert(NewOpc == AArch64ISD::TBNZ);
10096       NewOpc = AArch64ISD::TBZ;
10097     }
10098   }
10099
10100   SDLoc DL(N);
10101   return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10102                      DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10103 }
10104
10105 // vselect (v1i1 setcc) ->
10106 //     vselect (v1iXX setcc)  (XX is the size of the compared operand type)
10107 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10108 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10109 // such VSELECT.
10110 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10111   SDValue N0 = N->getOperand(0);
10112   EVT CCVT = N0.getValueType();
10113
10114   if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10115       CCVT.getVectorElementType() != MVT::i1)
10116     return SDValue();
10117
10118   EVT ResVT = N->getValueType(0);
10119   EVT CmpVT = N0.getOperand(0).getValueType();
10120   // Only combine when the result type is of the same size as the compared
10121   // operands.
10122   if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
10123     return SDValue();
10124
10125   SDValue IfTrue = N->getOperand(1);
10126   SDValue IfFalse = N->getOperand(2);
10127   SDValue SetCC =
10128       DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
10129                    N0.getOperand(0), N0.getOperand(1),
10130                    cast<CondCodeSDNode>(N0.getOperand(2))->get());
10131   return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
10132                      IfTrue, IfFalse);
10133 }
10134
10135 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
10136 /// the compare-mask instructions rather than going via NZCV, even if LHS and
10137 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
10138 /// with a vector one followed by a DUP shuffle on the result.
10139 static SDValue performSelectCombine(SDNode *N,
10140                                     TargetLowering::DAGCombinerInfo &DCI) {
10141   SelectionDAG &DAG = DCI.DAG;
10142   SDValue N0 = N->getOperand(0);
10143   EVT ResVT = N->getValueType(0);
10144
10145   if (N0.getOpcode() != ISD::SETCC)
10146     return SDValue();
10147
10148   // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
10149   // scalar SetCCResultType. We also don't expect vectors, because we assume
10150   // that selects fed by vector SETCCs are canonicalized to VSELECT.
10151   assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
10152          "Scalar-SETCC feeding SELECT has unexpected result type!");
10153
10154   // If NumMaskElts == 0, the comparison is larger than select result. The
10155   // largest real NEON comparison is 64-bits per lane, which means the result is
10156   // at most 32-bits and an illegal vector. Just bail out for now.
10157   EVT SrcVT = N0.getOperand(0).getValueType();
10158
10159   // Don't try to do this optimization when the setcc itself has i1 operands.
10160   // There are no legal vectors of i1, so this would be pointless.
10161   if (SrcVT == MVT::i1)
10162     return SDValue();
10163
10164   int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
10165   if (!ResVT.isVector() || NumMaskElts == 0)
10166     return SDValue();
10167
10168   SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
10169   EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
10170
10171   // Also bail out if the vector CCVT isn't the same size as ResVT.
10172   // This can happen if the SETCC operand size doesn't divide the ResVT size
10173   // (e.g., f64 vs v3f32).
10174   if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
10175     return SDValue();
10176
10177   // Make sure we didn't create illegal types, if we're not supposed to.
10178   assert(DCI.isBeforeLegalize() ||
10179          DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
10180
10181   // First perform a vector comparison, where lane 0 is the one we're interested
10182   // in.
10183   SDLoc DL(N0);
10184   SDValue LHS =
10185       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
10186   SDValue RHS =
10187       DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
10188   SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
10189
10190   // Now duplicate the comparison mask we want across all other lanes.
10191   SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
10192   SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
10193   Mask = DAG.getNode(ISD::BITCAST, DL,
10194                      ResVT.changeVectorElementTypeToInteger(), Mask);
10195
10196   return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
10197 }
10198
10199 /// Get rid of unnecessary NVCASTs (that don't change the type).
10200 static SDValue performNVCASTCombine(SDNode *N) {
10201   if (N->getValueType(0) == N->getOperand(0).getValueType())
10202     return N->getOperand(0);
10203
10204   return SDValue();
10205 }
10206
10207 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
10208                                                  DAGCombinerInfo &DCI) const {
10209   SelectionDAG &DAG = DCI.DAG;
10210   switch (N->getOpcode()) {
10211   default:
10212     break;
10213   case ISD::ADD:
10214   case ISD::SUB:
10215     return performAddSubLongCombine(N, DCI, DAG);
10216   case ISD::XOR:
10217     return performXorCombine(N, DAG, DCI, Subtarget);
10218   case ISD::MUL:
10219     return performMulCombine(N, DAG, DCI, Subtarget);
10220   case ISD::SINT_TO_FP:
10221   case ISD::UINT_TO_FP:
10222     return performIntToFpCombine(N, DAG, Subtarget);
10223   case ISD::FP_TO_SINT:
10224   case ISD::FP_TO_UINT:
10225     return performFpToIntCombine(N, DAG, DCI, Subtarget);
10226   case ISD::FDIV:
10227     return performFDivCombine(N, DAG, DCI, Subtarget);
10228   case ISD::OR:
10229     return performORCombine(N, DCI, Subtarget);
10230   case ISD::SRL:
10231     return performSRLCombine(N, DCI);
10232   case ISD::INTRINSIC_WO_CHAIN:
10233     return performIntrinsicCombine(N, DCI, Subtarget);
10234   case ISD::ANY_EXTEND:
10235   case ISD::ZERO_EXTEND:
10236   case ISD::SIGN_EXTEND:
10237     return performExtendCombine(N, DCI, DAG);
10238   case ISD::BITCAST:
10239     return performBitcastCombine(N, DCI, DAG);
10240   case ISD::CONCAT_VECTORS:
10241     return performConcatVectorsCombine(N, DCI, DAG);
10242   case ISD::SELECT:
10243     return performSelectCombine(N, DCI);
10244   case ISD::VSELECT:
10245     return performVSelectCombine(N, DCI.DAG);
10246   case ISD::LOAD:
10247     if (performTBISimplification(N->getOperand(1), DCI, DAG))
10248       return SDValue(N, 0);
10249     break;
10250   case ISD::STORE:
10251     return performSTORECombine(N, DCI, DAG, Subtarget);
10252   case AArch64ISD::BRCOND:
10253     return performBRCONDCombine(N, DCI, DAG);
10254   case AArch64ISD::TBNZ:
10255   case AArch64ISD::TBZ:
10256     return performTBZCombine(N, DCI, DAG);
10257   case AArch64ISD::CSEL:
10258     return performCONDCombine(N, DCI, DAG, 2, 3);
10259   case AArch64ISD::DUP:
10260     return performPostLD1Combine(N, DCI, false);
10261   case AArch64ISD::NVCAST:
10262     return performNVCASTCombine(N);
10263   case ISD::INSERT_VECTOR_ELT:
10264     return performPostLD1Combine(N, DCI, true);
10265   case ISD::INTRINSIC_VOID:
10266   case ISD::INTRINSIC_W_CHAIN:
10267     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10268     case Intrinsic::aarch64_neon_ld2:
10269     case Intrinsic::aarch64_neon_ld3:
10270     case Intrinsic::aarch64_neon_ld4:
10271     case Intrinsic::aarch64_neon_ld1x2:
10272     case Intrinsic::aarch64_neon_ld1x3:
10273     case Intrinsic::aarch64_neon_ld1x4:
10274     case Intrinsic::aarch64_neon_ld2lane:
10275     case Intrinsic::aarch64_neon_ld3lane:
10276     case Intrinsic::aarch64_neon_ld4lane:
10277     case Intrinsic::aarch64_neon_ld2r:
10278     case Intrinsic::aarch64_neon_ld3r:
10279     case Intrinsic::aarch64_neon_ld4r:
10280     case Intrinsic::aarch64_neon_st2:
10281     case Intrinsic::aarch64_neon_st3:
10282     case Intrinsic::aarch64_neon_st4:
10283     case Intrinsic::aarch64_neon_st1x2:
10284     case Intrinsic::aarch64_neon_st1x3:
10285     case Intrinsic::aarch64_neon_st1x4:
10286     case Intrinsic::aarch64_neon_st2lane:
10287     case Intrinsic::aarch64_neon_st3lane:
10288     case Intrinsic::aarch64_neon_st4lane:
10289       return performNEONPostLDSTCombine(N, DCI, DAG);
10290     default:
10291       break;
10292     }
10293   }
10294   return SDValue();
10295 }
10296
10297 // Check if the return value is used as only a return value, as otherwise
10298 // we can't perform a tail-call. In particular, we need to check for
10299 // target ISD nodes that are returns and any other "odd" constructs
10300 // that the generic analysis code won't necessarily catch.
10301 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
10302                                                SDValue &Chain) const {
10303   if (N->getNumValues() != 1)
10304     return false;
10305   if (!N->hasNUsesOfValue(1, 0))
10306     return false;
10307
10308   SDValue TCChain = Chain;
10309   SDNode *Copy = *N->use_begin();
10310   if (Copy->getOpcode() == ISD::CopyToReg) {
10311     // If the copy has a glue operand, we conservatively assume it isn't safe to
10312     // perform a tail call.
10313     if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
10314         MVT::Glue)
10315       return false;
10316     TCChain = Copy->getOperand(0);
10317   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
10318     return false;
10319
10320   bool HasRet = false;
10321   for (SDNode *Node : Copy->uses()) {
10322     if (Node->getOpcode() != AArch64ISD::RET_FLAG)
10323       return false;
10324     HasRet = true;
10325   }
10326
10327   if (!HasRet)
10328     return false;
10329
10330   Chain = TCChain;
10331   return true;
10332 }
10333
10334 // Return whether the an instruction can potentially be optimized to a tail
10335 // call. This will cause the optimizers to attempt to move, or duplicate,
10336 // return instructions to help enable tail call optimizations for this
10337 // instruction.
10338 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10339   return CI->isTailCall();
10340 }
10341
10342 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
10343                                                    SDValue &Offset,
10344                                                    ISD::MemIndexedMode &AM,
10345                                                    bool &IsInc,
10346                                                    SelectionDAG &DAG) const {
10347   if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
10348     return false;
10349
10350   Base = Op->getOperand(0);
10351   // All of the indexed addressing mode instructions take a signed
10352   // 9 bit immediate offset.
10353   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
10354     int64_t RHSC = RHS->getSExtValue();
10355     if (Op->getOpcode() == ISD::SUB)
10356       RHSC = -(uint64_t)RHSC;
10357     if (!isInt<9>(RHSC))
10358       return false;
10359     IsInc = (Op->getOpcode() == ISD::ADD);
10360     Offset = Op->getOperand(1);
10361     return true;
10362   }
10363   return false;
10364 }
10365
10366 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10367                                                       SDValue &Offset,
10368                                                       ISD::MemIndexedMode &AM,
10369                                                       SelectionDAG &DAG) const {
10370   EVT VT;
10371   SDValue Ptr;
10372   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10373     VT = LD->getMemoryVT();
10374     Ptr = LD->getBasePtr();
10375   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10376     VT = ST->getMemoryVT();
10377     Ptr = ST->getBasePtr();
10378   } else
10379     return false;
10380
10381   bool IsInc;
10382   if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10383     return false;
10384   AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10385   return true;
10386 }
10387
10388 bool AArch64TargetLowering::getPostIndexedAddressParts(
10389     SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10390     ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10391   EVT VT;
10392   SDValue Ptr;
10393   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10394     VT = LD->getMemoryVT();
10395     Ptr = LD->getBasePtr();
10396   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10397     VT = ST->getMemoryVT();
10398     Ptr = ST->getBasePtr();
10399   } else
10400     return false;
10401
10402   bool IsInc;
10403   if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10404     return false;
10405   // Post-indexing updates the base, so it's not a valid transform
10406   // if that's not the same as the load's pointer.
10407   if (Ptr != Base)
10408     return false;
10409   AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10410   return true;
10411 }
10412
10413 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10414                                   SelectionDAG &DAG) {
10415   SDLoc DL(N);
10416   SDValue Op = N->getOperand(0);
10417
10418   if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10419     return;
10420
10421   Op = SDValue(
10422       DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10423                          DAG.getUNDEF(MVT::i32), Op,
10424                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
10425       0);
10426   Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10427   Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10428 }
10429
10430 static void ReplaceReductionResults(SDNode *N,
10431                                     SmallVectorImpl<SDValue> &Results,
10432                                     SelectionDAG &DAG, unsigned InterOp,
10433                                     unsigned AcrossOp) {
10434   EVT LoVT, HiVT;
10435   SDValue Lo, Hi;
10436   SDLoc dl(N);
10437   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10438   std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10439   SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10440   SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10441   Results.push_back(SplitVal);
10442 }
10443
10444 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10445   SDLoc DL(N);
10446   SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10447   SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10448                            DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10449                                        DAG.getConstant(64, DL, MVT::i64)));
10450   return std::make_pair(Lo, Hi);
10451 }
10452
10453 static void ReplaceCMP_SWAP_128Results(SDNode *N,
10454                                        SmallVectorImpl<SDValue> & Results,
10455                                        SelectionDAG &DAG) {
10456   assert(N->getValueType(0) == MVT::i128 &&
10457          "AtomicCmpSwap on types less than 128 should be legal");
10458   auto Desired = splitInt128(N->getOperand(2), DAG);
10459   auto New = splitInt128(N->getOperand(3), DAG);
10460   SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
10461                    New.first,        New.second,    N->getOperand(0)};
10462   SDNode *CmpSwap = DAG.getMachineNode(
10463       AArch64::CMP_SWAP_128, SDLoc(N),
10464       DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10465
10466   MachineFunction &MF = DAG.getMachineFunction();
10467   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10468   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10469   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10470
10471   Results.push_back(SDValue(CmpSwap, 0));
10472   Results.push_back(SDValue(CmpSwap, 1));
10473   Results.push_back(SDValue(CmpSwap, 3));
10474 }
10475
10476 void AArch64TargetLowering::ReplaceNodeResults(
10477     SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10478   switch (N->getOpcode()) {
10479   default:
10480     llvm_unreachable("Don't know how to custom expand this");
10481   case ISD::BITCAST:
10482     ReplaceBITCASTResults(N, Results, DAG);
10483     return;
10484   case ISD::VECREDUCE_ADD:
10485   case ISD::VECREDUCE_SMAX:
10486   case ISD::VECREDUCE_SMIN:
10487   case ISD::VECREDUCE_UMAX:
10488   case ISD::VECREDUCE_UMIN:
10489     Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
10490     return;
10491
10492   case AArch64ISD::SADDV:
10493     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10494     return;
10495   case AArch64ISD::UADDV:
10496     ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10497     return;
10498   case AArch64ISD::SMINV:
10499     ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10500     return;
10501   case AArch64ISD::UMINV:
10502     ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10503     return;
10504   case AArch64ISD::SMAXV:
10505     ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10506     return;
10507   case AArch64ISD::UMAXV:
10508     ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10509     return;
10510   case ISD::FP_TO_UINT:
10511   case ISD::FP_TO_SINT:
10512     assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10513     // Let normal code take care of it by not adding anything to Results.
10514     return;
10515   case ISD::ATOMIC_CMP_SWAP:
10516     ReplaceCMP_SWAP_128Results(N, Results, DAG);
10517     return;
10518   }
10519 }
10520
10521 bool AArch64TargetLowering::useLoadStackGuardNode() const {
10522   if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
10523     return TargetLowering::useLoadStackGuardNode();
10524   return true;
10525 }
10526
10527 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
10528   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10529   // reciprocal if there are three or more FDIVs.
10530   return 3;
10531 }
10532
10533 TargetLoweringBase::LegalizeTypeAction
10534 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10535   MVT SVT = VT.getSimpleVT();
10536   // During type legalization, we prefer to widen v1i8, v1i16, v1i32  to v8i8,
10537   // v4i16, v2i32 instead of to promote.
10538   if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10539       || SVT == MVT::v1f32)
10540     return TypeWidenVector;
10541
10542   return TargetLoweringBase::getPreferredVectorAction(VT);
10543 }
10544
10545 // Loads and stores less than 128-bits are already atomic; ones above that
10546 // are doomed anyway, so defer to the default libcall and blame the OS when
10547 // things go wrong.
10548 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10549   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10550   return Size == 128;
10551 }
10552
10553 // Loads and stores less than 128-bits are already atomic; ones above that
10554 // are doomed anyway, so defer to the default libcall and blame the OS when
10555 // things go wrong.
10556 TargetLowering::AtomicExpansionKind
10557 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
10558   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
10559   return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10560 }
10561
10562 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
10563 TargetLowering::AtomicExpansionKind
10564 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10565   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10566   return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10567 }
10568
10569 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10570     AtomicCmpXchgInst *AI) const {
10571   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10572   // implement cmpxchg without spilling. If the address being exchanged is also
10573   // on the stack and close enough to the spill slot, this can lead to a
10574   // situation where the monitor always gets cleared and the atomic operation
10575   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10576   return getTargetMachine().getOptLevel() != 0;
10577 }
10578
10579 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10580                                              AtomicOrdering Ord) const {
10581   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10582   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10583   bool IsAcquire = isAcquireOrStronger(Ord);
10584
10585   // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10586   // intrinsic must return {i64, i64} and we have to recombine them into a
10587   // single i128 here.
10588   if (ValTy->getPrimitiveSizeInBits() == 128) {
10589     Intrinsic::ID Int =
10590         IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10591     Function *Ldxr = Intrinsic::getDeclaration(M, Int);
10592
10593     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10594     Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10595
10596     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10597     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10598     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10599     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10600     return Builder.CreateOr(
10601         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10602   }
10603
10604   Type *Tys[] = { Addr->getType() };
10605   Intrinsic::ID Int =
10606       IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10607   Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
10608
10609   return Builder.CreateTruncOrBitCast(
10610       Builder.CreateCall(Ldxr, Addr),
10611       cast<PointerType>(Addr->getType())->getElementType());
10612 }
10613
10614 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10615     IRBuilder<> &Builder) const {
10616   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10617   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10618 }
10619
10620 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10621                                                    Value *Val, Value *Addr,
10622                                                    AtomicOrdering Ord) const {
10623   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10624   bool IsRelease = isReleaseOrStronger(Ord);
10625
10626   // Since the intrinsics must have legal type, the i128 intrinsics take two
10627   // parameters: "i64, i64". We must marshal Val into the appropriate form
10628   // before the call.
10629   if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10630     Intrinsic::ID Int =
10631         IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10632     Function *Stxr = Intrinsic::getDeclaration(M, Int);
10633     Type *Int64Ty = Type::getInt64Ty(M->getContext());
10634
10635     Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10636     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10637     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10638     return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
10639   }
10640
10641   Intrinsic::ID Int =
10642       IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10643   Type *Tys[] = { Addr->getType() };
10644   Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10645
10646   return Builder.CreateCall(Stxr,
10647                             {Builder.CreateZExtOrBitCast(
10648                                  Val, Stxr->getFunctionType()->getParamType(0)),
10649                              Addr});
10650 }
10651
10652 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10653     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10654   return Ty->isArrayTy();
10655 }
10656
10657 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10658                                                             EVT) const {
10659   return false;
10660 }
10661
10662 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
10663   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10664   Function *ThreadPointerFunc =
10665       Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
10666   return IRB.CreatePointerCast(
10667       IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), Offset),
10668       Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10669 }
10670
10671 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
10672   // Android provides a fixed TLS slot for the stack cookie. See the definition
10673   // of TLS_SLOT_STACK_GUARD in
10674   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10675   if (Subtarget->isTargetAndroid())
10676     return UseTlsOffset(IRB, 0x28);
10677
10678   // Fuchsia is similar.
10679   // <magenta/tls.h> defines MX_TLS_STACK_GUARD_OFFSET with this value.
10680   if (Subtarget->isTargetFuchsia())
10681     return UseTlsOffset(IRB, -0x10);
10682
10683   return TargetLowering::getIRStackGuard(IRB);
10684 }
10685
10686 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10687   // Android provides a fixed TLS slot for the SafeStack pointer. See the
10688   // definition of TLS_SLOT_SAFESTACK in
10689   // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10690   if (Subtarget->isTargetAndroid())
10691     return UseTlsOffset(IRB, 0x48);
10692
10693   // Fuchsia is similar.
10694   // <magenta/tls.h> defines MX_TLS_UNSAFE_SP_OFFSET with this value.
10695   if (Subtarget->isTargetFuchsia())
10696     return UseTlsOffset(IRB, -0x8);
10697
10698   return TargetLowering::getSafeStackPointerLocation(IRB);
10699 }
10700
10701 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
10702     const Instruction &AndI) const {
10703   // Only sink 'and' mask to cmp use block if it is masking a single bit, since
10704   // this is likely to be fold the and/cmp/br into a single tbz instruction.  It
10705   // may be beneficial to sink in other cases, but we would have to check that
10706   // the cmp would not get folded into the br to form a cbz for these to be
10707   // beneficial.
10708   ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
10709   if (!Mask)
10710     return false;
10711   return Mask->getUniqueInteger().isPowerOf2();
10712 }
10713
10714 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10715   // Update IsSplitCSR in AArch64unctionInfo.
10716   AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10717   AFI->setIsSplitCSR(true);
10718 }
10719
10720 void AArch64TargetLowering::insertCopiesSplitCSR(
10721     MachineBasicBlock *Entry,
10722     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10723   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10724   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10725   if (!IStart)
10726     return;
10727
10728   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10729   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
10730   MachineBasicBlock::iterator MBBI = Entry->begin();
10731   for (const MCPhysReg *I = IStart; *I; ++I) {
10732     const TargetRegisterClass *RC = nullptr;
10733     if (AArch64::GPR64RegClass.contains(*I))
10734       RC = &AArch64::GPR64RegClass;
10735     else if (AArch64::FPR64RegClass.contains(*I))
10736       RC = &AArch64::FPR64RegClass;
10737     else
10738       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10739
10740     unsigned NewVR = MRI->createVirtualRegister(RC);
10741     // Create copy from CSR to a virtual register.
10742     // FIXME: this currently does not emit CFI pseudo-instructions, it works
10743     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10744     // nounwind. If we want to generalize this later, we may need to emit
10745     // CFI pseudo-instructions.
10746     assert(Entry->getParent()->getFunction()->hasFnAttribute(
10747                Attribute::NoUnwind) &&
10748            "Function should be nounwind in insertCopiesSplitCSR!");
10749     Entry->addLiveIn(*I);
10750     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
10751         .addReg(*I);
10752
10753     // Insert the copy-back instructions right before the terminator.
10754     for (auto *Exit : Exits)
10755       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10756               TII->get(TargetOpcode::COPY), *I)
10757           .addReg(NewVR);
10758   }
10759 }
10760
10761 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
10762   // Integer division on AArch64 is expensive. However, when aggressively
10763   // optimizing for code size, we prefer to use a div instruction, as it is
10764   // usually smaller than the alternative sequence.
10765   // The exception to this is vector division. Since AArch64 doesn't have vector
10766   // integer division, leaving the division as-is is a loss even in terms of
10767   // size, because it will have to be scalarized, while the alternative code
10768   // sequence can be performed in vector form.
10769   bool OptSize =
10770       Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
10771   return OptSize && !VT.isVector();
10772 }
10773
10774 unsigned
10775 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
10776   if (Subtarget->isTargetDarwin())
10777     return getPointerTy(DL).getSizeInBits();
10778
10779   return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
10780 }