Renamed CCState members that appear to misspell 'Processed' as 'Proceed'. NFC.
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalValue.h"
40 #include "llvm/IR/IRBuilder.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <utility>
52 using namespace llvm;
53
54 #define DEBUG_TYPE "arm-isel"
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
58 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
59
60 cl::opt<bool>
61 EnableARMLongCalls("arm-long-calls", cl::Hidden,
62   cl::desc("Generate calls via indirect call instructions"),
63   cl::init(false));
64
65 static cl::opt<bool>
66 ARMInterworking("arm-interworking", cl::Hidden,
67   cl::desc("Enable / disable ARM interworking (for debugging only)"),
68   cl::init(true));
69
70 namespace {
71   class ARMCCState : public CCState {
72   public:
73     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
74                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
75                ParmContext PC)
76         : CCState(CC, isVarArg, MF, locs, C) {
77       assert(((PC == Call) || (PC == Prologue)) &&
78              "ARMCCState users must specify whether their context is call"
79              "or prologue generation.");
80       CallOrPrologue = PC;
81     }
82   };
83 }
84
85 // The APCS parameter registers.
86 static const MCPhysReg GPRArgRegs[] = {
87   ARM::R0, ARM::R1, ARM::R2, ARM::R3
88 };
89
90 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
91                                        MVT PromotedBitwiseVT) {
92   if (VT != PromotedLdStVT) {
93     setOperationAction(ISD::LOAD, VT, Promote);
94     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
95
96     setOperationAction(ISD::STORE, VT, Promote);
97     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
98   }
99
100   MVT ElemTy = VT.getVectorElementType();
101   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
102     setOperationAction(ISD::SETCC, VT, Custom);
103   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
104   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
105   if (ElemTy == MVT::i32) {
106     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
107     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
108     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
109     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
110   } else {
111     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
112     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
113     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
114     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
115   }
116   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
117   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
118   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
119   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
120   setOperationAction(ISD::SELECT,            VT, Expand);
121   setOperationAction(ISD::SELECT_CC,         VT, Expand);
122   setOperationAction(ISD::VSELECT,           VT, Expand);
123   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
124   if (VT.isInteger()) {
125     setOperationAction(ISD::SHL, VT, Custom);
126     setOperationAction(ISD::SRA, VT, Custom);
127     setOperationAction(ISD::SRL, VT, Custom);
128   }
129
130   // Promote all bit-wise operations.
131   if (VT.isInteger() && VT != PromotedBitwiseVT) {
132     setOperationAction(ISD::AND, VT, Promote);
133     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
134     setOperationAction(ISD::OR,  VT, Promote);
135     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
136     setOperationAction(ISD::XOR, VT, Promote);
137     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
138   }
139
140   // Neon does not support vector divide/remainder operations.
141   setOperationAction(ISD::SDIV, VT, Expand);
142   setOperationAction(ISD::UDIV, VT, Expand);
143   setOperationAction(ISD::FDIV, VT, Expand);
144   setOperationAction(ISD::SREM, VT, Expand);
145   setOperationAction(ISD::UREM, VT, Expand);
146   setOperationAction(ISD::FREM, VT, Expand);
147 }
148
149 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
150   addRegisterClass(VT, &ARM::DPRRegClass);
151   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
152 }
153
154 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
155   addRegisterClass(VT, &ARM::DPairRegClass);
156   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
157 }
158
159 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
160   if (TT.isOSBinFormatMachO())
161     return new TargetLoweringObjectFileMachO();
162   if (TT.isOSWindows())
163     return new TargetLoweringObjectFileCOFF();
164   return new ARMElfTargetObjectFile();
165 }
166
167 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM)
168     : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
169   Subtarget = &TM.getSubtarget<ARMSubtarget>();
170   RegInfo = TM.getSubtargetImpl()->getRegisterInfo();
171   Itins = TM.getSubtargetImpl()->getInstrItineraryData();
172
173   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
174
175   if (Subtarget->isTargetMachO()) {
176     // Uses VFP for Thumb libfuncs if available.
177     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
178         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
179       // Single-precision floating-point arithmetic.
180       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
181       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
182       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
183       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
184
185       // Double-precision floating-point arithmetic.
186       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
187       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
188       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
189       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
190
191       // Single-precision comparisons.
192       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
193       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
194       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
195       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
196       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
197       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
198       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
199       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
200
201       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
208       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
209
210       // Double-precision comparisons.
211       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
212       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
213       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
214       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
215       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
216       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
217       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
218       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
219
220       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
227       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
228
229       // Floating-point to integer conversions.
230       // i64 conversions are done via library routines even when generating VFP
231       // instructions, so use the same ones.
232       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
233       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
234       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
235       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
236
237       // Conversions between floating types.
238       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
239       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
240
241       // Integer to floating-point conversions.
242       // i64 conversions are done via library routines even when generating VFP
243       // instructions, so use the same ones.
244       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
245       // e.g., __floatunsidf vs. __floatunssidfvfp.
246       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
247       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
248       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
249       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
250     }
251   }
252
253   // These libcalls are not available in 32-bit.
254   setLibcallName(RTLIB::SHL_I128, nullptr);
255   setLibcallName(RTLIB::SRL_I128, nullptr);
256   setLibcallName(RTLIB::SRA_I128, nullptr);
257
258   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
259       !Subtarget->isTargetWindows()) {
260     static const struct {
261       const RTLIB::Libcall Op;
262       const char * const Name;
263       const CallingConv::ID CC;
264       const ISD::CondCode Cond;
265     } LibraryCalls[] = {
266       // Double-precision floating-point arithmetic helper functions
267       // RTABI chapter 4.1.2, Table 2
268       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
269       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
271       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
272
273       // Double-precision floating-point comparison helper functions
274       // RTABI chapter 4.1.2, Table 3
275       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
276       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
277       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
278       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
279       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
280       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
281       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
282       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
283
284       // Single-precision floating-point arithmetic helper functions
285       // RTABI chapter 4.1.2, Table 4
286       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
287       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
289       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
290
291       // Single-precision floating-point comparison helper functions
292       // RTABI chapter 4.1.2, Table 5
293       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
294       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
295       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
296       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
297       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
298       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
299       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
300       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
301
302       // Floating-point to integer conversions.
303       // RTABI chapter 4.1.2, Table 6
304       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312
313       // Conversions between floating types.
314       // RTABI chapter 4.1.2, Table 7
315       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318
319       // Integer to floating-point conversions.
320       // RTABI chapter 4.1.2, Table 8
321       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329
330       // Long long helper functions
331       // RTABI chapter 4.2, Table 9
332       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336
337       // Integer division functions
338       // RTABI chapter 4.3.1
339       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347
348       // Memory operations
349       // RTABI chapter 4.3.4
350       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
353     };
354
355     for (const auto &LC : LibraryCalls) {
356       setLibcallName(LC.Op, LC.Name);
357       setLibcallCallingConv(LC.Op, LC.CC);
358       if (LC.Cond != ISD::SETCC_INVALID)
359         setCmpLibcallCC(LC.Op, LC.Cond);
360     }
361   }
362
363   if (Subtarget->isTargetWindows()) {
364     static const struct {
365       const RTLIB::Libcall Op;
366       const char * const Name;
367       const CallingConv::ID CC;
368     } LibraryCalls[] = {
369       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
371       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
372       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
373       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
374       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
375       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
376       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
377     };
378
379     for (const auto &LC : LibraryCalls) {
380       setLibcallName(LC.Op, LC.Name);
381       setLibcallCallingConv(LC.Op, LC.CC);
382     }
383   }
384
385   // Use divmod compiler-rt calls for iOS 5.0 and later.
386   if (Subtarget->getTargetTriple().isiOS() &&
387       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
388     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
389     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
390   }
391
392   // The half <-> float conversion functions are always soft-float, but are
393   // needed for some targets which use a hard-float calling convention by
394   // default.
395   if (Subtarget->isAAPCS_ABI()) {
396     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
397     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
398     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
399   } else {
400     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
401     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
402     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
403   }
404
405   if (Subtarget->isThumb1Only())
406     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
407   else
408     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
409   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
410       !Subtarget->isThumb1Only()) {
411     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
412     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
413   }
414
415   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
416        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
417     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
418          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
419       setTruncStoreAction((MVT::SimpleValueType)VT,
420                           (MVT::SimpleValueType)InnerVT, Expand);
421     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
422     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
423     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
424
425     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
426     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
427     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
428     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
429
430     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
431   }
432
433   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
434   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
435
436   if (Subtarget->hasNEON()) {
437     addDRTypeForNEON(MVT::v2f32);
438     addDRTypeForNEON(MVT::v8i8);
439     addDRTypeForNEON(MVT::v4i16);
440     addDRTypeForNEON(MVT::v2i32);
441     addDRTypeForNEON(MVT::v1i64);
442
443     addQRTypeForNEON(MVT::v4f32);
444     addQRTypeForNEON(MVT::v2f64);
445     addQRTypeForNEON(MVT::v16i8);
446     addQRTypeForNEON(MVT::v8i16);
447     addQRTypeForNEON(MVT::v4i32);
448     addQRTypeForNEON(MVT::v2i64);
449
450     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
451     // neither Neon nor VFP support any arithmetic operations on it.
452     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
453     // supported for v4f32.
454     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
455     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
456     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
457     // FIXME: Code duplication: FDIV and FREM are expanded always, see
458     // ARMTargetLowering::addTypeForNEON method for details.
459     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
460     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
461     // FIXME: Create unittest.
462     // In another words, find a way when "copysign" appears in DAG with vector
463     // operands.
464     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
465     // FIXME: Code duplication: SETCC has custom operation action, see
466     // ARMTargetLowering::addTypeForNEON method for details.
467     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
468     // FIXME: Create unittest for FNEG and for FABS.
469     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
470     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
471     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
472     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
473     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
474     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
475     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
476     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
477     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
478     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
479     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
480     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
481     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
482     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
483     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
484     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
485     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
486     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
487     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
488
489     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
490     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
491     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
492     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
493     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
494     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
495     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
496     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
497     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
498     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
499     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
500     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
501     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
502     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
503     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
504
505     // Mark v2f32 intrinsics.
506     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
507     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
508     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
509     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
510     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
511     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
512     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
513     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
514     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
515     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
516     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
517     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
518     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
519     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
520     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
521
522     // Neon does not support some operations on v1i64 and v2i64 types.
523     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
524     // Custom handling for some quad-vector types to detect VMULL.
525     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
526     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
527     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
528     // Custom handling for some vector types to avoid expensive expansions
529     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
530     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
531     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
532     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
533     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
534     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
535     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
536     // a destination type that is wider than the source, and nor does
537     // it have a FP_TO_[SU]INT instruction with a narrower destination than
538     // source.
539     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
540     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
541     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
542     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
543
544     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
545     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
546
547     // NEON does not have single instruction CTPOP for vectors with element
548     // types wider than 8-bits.  However, custom lowering can leverage the
549     // v8i8/v16i8 vcnt instruction.
550     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
551     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
552     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
553     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
554
555     // NEON only has FMA instructions as of VFP4.
556     if (!Subtarget->hasVFP4()) {
557       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
558       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
559     }
560
561     setTargetDAGCombine(ISD::INTRINSIC_VOID);
562     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
563     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
564     setTargetDAGCombine(ISD::SHL);
565     setTargetDAGCombine(ISD::SRL);
566     setTargetDAGCombine(ISD::SRA);
567     setTargetDAGCombine(ISD::SIGN_EXTEND);
568     setTargetDAGCombine(ISD::ZERO_EXTEND);
569     setTargetDAGCombine(ISD::ANY_EXTEND);
570     setTargetDAGCombine(ISD::SELECT_CC);
571     setTargetDAGCombine(ISD::BUILD_VECTOR);
572     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
573     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
574     setTargetDAGCombine(ISD::STORE);
575     setTargetDAGCombine(ISD::FP_TO_SINT);
576     setTargetDAGCombine(ISD::FP_TO_UINT);
577     setTargetDAGCombine(ISD::FDIV);
578
579     // It is legal to extload from v4i8 to v4i16 or v4i32.
580     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
581                   MVT::v4i16, MVT::v2i16,
582                   MVT::v2i32};
583     for (unsigned i = 0; i < 6; ++i) {
584       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
585       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
586       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
587     }
588   }
589
590   // ARM and Thumb2 support UMLAL/SMLAL.
591   if (!Subtarget->isThumb1Only())
592     setTargetDAGCombine(ISD::ADDC);
593
594   if (Subtarget->isFPOnlySP()) {
595     // When targetting a floating-point unit with only single-precision
596     // operations, f64 is legal for the few double-precision instructions which
597     // are present However, no double-precision operations other than moves,
598     // loads and stores are provided by the hardware.
599     setOperationAction(ISD::FADD,       MVT::f64, Expand);
600     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
601     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
602     setOperationAction(ISD::FMA,        MVT::f64, Expand);
603     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
604     setOperationAction(ISD::FREM,       MVT::f64, Expand);
605     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
606     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
607     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
608     setOperationAction(ISD::FABS,       MVT::f64, Expand);
609     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
610     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
611     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
612     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
613     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
614     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
615     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
616     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
617     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
618     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
619     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
620     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
621     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
622     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
623     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
624     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
625     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
626   }
627
628   computeRegisterProperties();
629
630   // ARM does not have floating-point extending loads.
631   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
632   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
633
634   // ... or truncating stores
635   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
636   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
637   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
638
639   // ARM does not have i1 sign extending load.
640   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
641
642   // ARM supports all 4 flavors of integer indexed load / store.
643   if (!Subtarget->isThumb1Only()) {
644     for (unsigned im = (unsigned)ISD::PRE_INC;
645          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
646       setIndexedLoadAction(im,  MVT::i1,  Legal);
647       setIndexedLoadAction(im,  MVT::i8,  Legal);
648       setIndexedLoadAction(im,  MVT::i16, Legal);
649       setIndexedLoadAction(im,  MVT::i32, Legal);
650       setIndexedStoreAction(im, MVT::i1,  Legal);
651       setIndexedStoreAction(im, MVT::i8,  Legal);
652       setIndexedStoreAction(im, MVT::i16, Legal);
653       setIndexedStoreAction(im, MVT::i32, Legal);
654     }
655   }
656
657   setOperationAction(ISD::SADDO, MVT::i32, Custom);
658   setOperationAction(ISD::UADDO, MVT::i32, Custom);
659   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
660   setOperationAction(ISD::USUBO, MVT::i32, Custom);
661
662   // i64 operation support.
663   setOperationAction(ISD::MUL,     MVT::i64, Expand);
664   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
665   if (Subtarget->isThumb1Only()) {
666     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
667     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
668   }
669   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
670       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
671     setOperationAction(ISD::MULHS, MVT::i32, Expand);
672
673   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
674   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
675   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
676   setOperationAction(ISD::SRL,       MVT::i64, Custom);
677   setOperationAction(ISD::SRA,       MVT::i64, Custom);
678
679   if (!Subtarget->isThumb1Only()) {
680     // FIXME: We should do this for Thumb1 as well.
681     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
682     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
683     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
684     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
685   }
686
687   // ARM does not have ROTL.
688   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
689   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
690   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
691   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
692     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
693
694   // These just redirect to CTTZ and CTLZ on ARM.
695   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
696   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
697
698   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
699
700   // Only ARMv6 has BSWAP.
701   if (!Subtarget->hasV6Ops())
702     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
703
704   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
705       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
706     // These are expanded into libcalls if the cpu doesn't have HW divider.
707     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
708     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
709   }
710
711   // FIXME: Also set divmod for SREM on EABI
712   setOperationAction(ISD::SREM,  MVT::i32, Expand);
713   setOperationAction(ISD::UREM,  MVT::i32, Expand);
714   // Register based DivRem for AEABI (RTABI 4.2)
715   if (Subtarget->isTargetAEABI()) {
716     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
717     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
718     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
719     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
720     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
721     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
722     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
723     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
724
725     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
726     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
727     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
728     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
729     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
730     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
731     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
732     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
733
734     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
735     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
736   } else {
737     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
738     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
739   }
740
741   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
742   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
743   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
744   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
745   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
746
747   setOperationAction(ISD::TRAP, MVT::Other, Legal);
748
749   // Use the default implementation.
750   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
751   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
752   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
753   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
754   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
755   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
756
757   if (!Subtarget->isTargetMachO()) {
758     // Non-MachO platforms may return values in these registers via the
759     // personality function.
760     setExceptionPointerRegister(ARM::R0);
761     setExceptionSelectorRegister(ARM::R1);
762   }
763
764   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
765     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
766   else
767     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
768
769   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
770   // the default expansion. If we are targeting a single threaded system,
771   // then set them all for expand so we can lower them later into their
772   // non-atomic form.
773   if (TM.Options.ThreadModel == ThreadModel::Single)
774     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
775   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
776     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
777     // to ldrex/strex loops already.
778     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
779
780     // On v8, we have particularly efficient implementations of atomic fences
781     // if they can be combined with nearby atomic loads and stores.
782     if (!Subtarget->hasV8Ops()) {
783       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
784       setInsertFencesForAtomic(true);
785     }
786   } else {
787     // If there's anything we can use as a barrier, go through custom lowering
788     // for ATOMIC_FENCE.
789     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
790                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
791
792     // Set them all for expansion, which will force libcalls.
793     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
794     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
795     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
796     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
797     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
798     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
799     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
800     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
801     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
802     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
803     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
804     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
805     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
806     // Unordered/Monotonic case.
807     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
808     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
809   }
810
811   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
812
813   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
814   if (!Subtarget->hasV6Ops()) {
815     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
816     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
817   }
818   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
819
820   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
821       !Subtarget->isThumb1Only()) {
822     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
823     // iff target supports vfp2.
824     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
825     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
826   }
827
828   // We want to custom lower some of our intrinsics.
829   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
830   if (Subtarget->isTargetDarwin()) {
831     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
832     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
833     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
834   }
835
836   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
837   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
838   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
839   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
840   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
841   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
842   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
843   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
844   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
845
846   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
847   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
848   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
849   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
850   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
851
852   // We don't support sin/cos/fmod/copysign/pow
853   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
854   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
855   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
856   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
857   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
858   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
859   setOperationAction(ISD::FREM,      MVT::f64, Expand);
860   setOperationAction(ISD::FREM,      MVT::f32, Expand);
861   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
862       !Subtarget->isThumb1Only()) {
863     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
864     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
865   }
866   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
867   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
868
869   if (!Subtarget->hasVFP4()) {
870     setOperationAction(ISD::FMA, MVT::f64, Expand);
871     setOperationAction(ISD::FMA, MVT::f32, Expand);
872   }
873
874   // Various VFP goodness
875   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
876     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
877     if (Subtarget->hasVFP2()) {
878       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
879       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
880       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
881       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
882     }
883
884     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
885     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
886       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
887       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
888     }
889
890     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
891     if (!Subtarget->hasFP16()) {
892       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
893       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
894     }
895   }
896
897   // Combine sin / cos into one node or libcall if possible.
898   if (Subtarget->hasSinCos()) {
899     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
900     setLibcallName(RTLIB::SINCOS_F64, "sincos");
901     if (Subtarget->getTargetTriple().isiOS()) {
902       // For iOS, we don't want to the normal expansion of a libcall to
903       // sincos. We want to issue a libcall to __sincos_stret.
904       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
905       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
906     }
907   }
908
909   // FP-ARMv8 implements a lot of rounding-like FP operations.
910   if (Subtarget->hasFPARMv8()) {
911     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
912     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
913     setOperationAction(ISD::FROUND, MVT::f32, Legal);
914     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
915     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
916     setOperationAction(ISD::FRINT, MVT::f32, Legal);
917     if (!Subtarget->isFPOnlySP()) {
918       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
919       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
920       setOperationAction(ISD::FROUND, MVT::f64, Legal);
921       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
922       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
923       setOperationAction(ISD::FRINT, MVT::f64, Legal);
924     }
925   }
926   // We have target-specific dag combine patterns for the following nodes:
927   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
928   setTargetDAGCombine(ISD::ADD);
929   setTargetDAGCombine(ISD::SUB);
930   setTargetDAGCombine(ISD::MUL);
931   setTargetDAGCombine(ISD::AND);
932   setTargetDAGCombine(ISD::OR);
933   setTargetDAGCombine(ISD::XOR);
934
935   if (Subtarget->hasV6Ops())
936     setTargetDAGCombine(ISD::SRL);
937
938   setStackPointerRegisterToSaveRestore(ARM::SP);
939
940   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
941       !Subtarget->hasVFP2())
942     setSchedulingPreference(Sched::RegPressure);
943   else
944     setSchedulingPreference(Sched::Hybrid);
945
946   //// temporary - rewrite interface to use type
947   MaxStoresPerMemset = 8;
948   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
949   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
950   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
951   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
952   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
953
954   // On ARM arguments smaller than 4 bytes are extended, so all arguments
955   // are at least 4 bytes aligned.
956   setMinStackArgumentAlignment(4);
957
958   // Prefer likely predicted branches to selects on out-of-order cores.
959   PredictableSelectIsExpensive = Subtarget->isLikeA9();
960
961   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
962 }
963
964 // FIXME: It might make sense to define the representative register class as the
965 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
966 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
967 // SPR's representative would be DPR_VFP2. This should work well if register
968 // pressure tracking were modified such that a register use would increment the
969 // pressure of the register class's representative and all of it's super
970 // classes' representatives transitively. We have not implemented this because
971 // of the difficulty prior to coalescing of modeling operand register classes
972 // due to the common occurrence of cross class copies and subregister insertions
973 // and extractions.
974 std::pair<const TargetRegisterClass*, uint8_t>
975 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
976   const TargetRegisterClass *RRC = nullptr;
977   uint8_t Cost = 1;
978   switch (VT.SimpleTy) {
979   default:
980     return TargetLowering::findRepresentativeClass(VT);
981   // Use DPR as representative register class for all floating point
982   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
983   // the cost is 1 for both f32 and f64.
984   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
985   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
986     RRC = &ARM::DPRRegClass;
987     // When NEON is used for SP, only half of the register file is available
988     // because operations that define both SP and DP results will be constrained
989     // to the VFP2 class (D0-D15). We currently model this constraint prior to
990     // coalescing by double-counting the SP regs. See the FIXME above.
991     if (Subtarget->useNEONForSinglePrecisionFP())
992       Cost = 2;
993     break;
994   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
995   case MVT::v4f32: case MVT::v2f64:
996     RRC = &ARM::DPRRegClass;
997     Cost = 2;
998     break;
999   case MVT::v4i64:
1000     RRC = &ARM::DPRRegClass;
1001     Cost = 4;
1002     break;
1003   case MVT::v8i64:
1004     RRC = &ARM::DPRRegClass;
1005     Cost = 8;
1006     break;
1007   }
1008   return std::make_pair(RRC, Cost);
1009 }
1010
1011 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1012   switch (Opcode) {
1013   default: return nullptr;
1014   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1015   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1016   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1017   case ARMISD::CALL:          return "ARMISD::CALL";
1018   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1019   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1020   case ARMISD::tCALL:         return "ARMISD::tCALL";
1021   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1022   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1023   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1024   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1025   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1026   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1027   case ARMISD::CMP:           return "ARMISD::CMP";
1028   case ARMISD::CMN:           return "ARMISD::CMN";
1029   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1030   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1031   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1032   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1033   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1034
1035   case ARMISD::CMOV:          return "ARMISD::CMOV";
1036
1037   case ARMISD::RBIT:          return "ARMISD::RBIT";
1038
1039   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1040   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1041   case ARMISD::SITOF:         return "ARMISD::SITOF";
1042   case ARMISD::UITOF:         return "ARMISD::UITOF";
1043
1044   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1045   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1046   case ARMISD::RRX:           return "ARMISD::RRX";
1047
1048   case ARMISD::ADDC:          return "ARMISD::ADDC";
1049   case ARMISD::ADDE:          return "ARMISD::ADDE";
1050   case ARMISD::SUBC:          return "ARMISD::SUBC";
1051   case ARMISD::SUBE:          return "ARMISD::SUBE";
1052
1053   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1054   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1055
1056   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1057   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1058
1059   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1060
1061   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1062
1063   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1064
1065   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1066
1067   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1068
1069   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1070
1071   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1072   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1073   case ARMISD::VCGE:          return "ARMISD::VCGE";
1074   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1075   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1076   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1077   case ARMISD::VCGT:          return "ARMISD::VCGT";
1078   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1079   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1080   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1081   case ARMISD::VTST:          return "ARMISD::VTST";
1082
1083   case ARMISD::VSHL:          return "ARMISD::VSHL";
1084   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1085   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1086   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1087   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1088   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1089   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1090   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1091   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1092   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1093   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1094   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1095   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1096   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1097   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1098   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1099   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1100   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1101   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1102   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1103   case ARMISD::VDUP:          return "ARMISD::VDUP";
1104   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1105   case ARMISD::VEXT:          return "ARMISD::VEXT";
1106   case ARMISD::VREV64:        return "ARMISD::VREV64";
1107   case ARMISD::VREV32:        return "ARMISD::VREV32";
1108   case ARMISD::VREV16:        return "ARMISD::VREV16";
1109   case ARMISD::VZIP:          return "ARMISD::VZIP";
1110   case ARMISD::VUZP:          return "ARMISD::VUZP";
1111   case ARMISD::VTRN:          return "ARMISD::VTRN";
1112   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1113   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1114   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1115   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1116   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1117   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1118   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1119   case ARMISD::FMAX:          return "ARMISD::FMAX";
1120   case ARMISD::FMIN:          return "ARMISD::FMIN";
1121   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1122   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1123   case ARMISD::BFI:           return "ARMISD::BFI";
1124   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1125   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1126   case ARMISD::VBSL:          return "ARMISD::VBSL";
1127   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1128   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1129   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1130   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1131   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1132   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1133   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1134   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1135   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1136   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1137   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1138   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1139   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1140   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1141   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1142   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1143   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1144   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1145   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1146   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1147   }
1148 }
1149
1150 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1151   if (!VT.isVector()) return getPointerTy();
1152   return VT.changeVectorElementTypeToInteger();
1153 }
1154
1155 /// getRegClassFor - Return the register class that should be used for the
1156 /// specified value type.
1157 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1158   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1159   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1160   // load / store 4 to 8 consecutive D registers.
1161   if (Subtarget->hasNEON()) {
1162     if (VT == MVT::v4i64)
1163       return &ARM::QQPRRegClass;
1164     if (VT == MVT::v8i64)
1165       return &ARM::QQQQPRRegClass;
1166   }
1167   return TargetLowering::getRegClassFor(VT);
1168 }
1169
1170 // Create a fast isel object.
1171 FastISel *
1172 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1173                                   const TargetLibraryInfo *libInfo) const {
1174   return ARM::createFastISel(funcInfo, libInfo);
1175 }
1176
1177 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1178 /// be used for loads / stores from the global.
1179 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1180   return (Subtarget->isThumb1Only() ? 127 : 4095);
1181 }
1182
1183 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1184   unsigned NumVals = N->getNumValues();
1185   if (!NumVals)
1186     return Sched::RegPressure;
1187
1188   for (unsigned i = 0; i != NumVals; ++i) {
1189     EVT VT = N->getValueType(i);
1190     if (VT == MVT::Glue || VT == MVT::Other)
1191       continue;
1192     if (VT.isFloatingPoint() || VT.isVector())
1193       return Sched::ILP;
1194   }
1195
1196   if (!N->isMachineOpcode())
1197     return Sched::RegPressure;
1198
1199   // Load are scheduled for latency even if there instruction itinerary
1200   // is not available.
1201   const TargetInstrInfo *TII =
1202       getTargetMachine().getSubtargetImpl()->getInstrInfo();
1203   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1204
1205   if (MCID.getNumDefs() == 0)
1206     return Sched::RegPressure;
1207   if (!Itins->isEmpty() &&
1208       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1209     return Sched::ILP;
1210
1211   return Sched::RegPressure;
1212 }
1213
1214 //===----------------------------------------------------------------------===//
1215 // Lowering Code
1216 //===----------------------------------------------------------------------===//
1217
1218 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1219 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1220   switch (CC) {
1221   default: llvm_unreachable("Unknown condition code!");
1222   case ISD::SETNE:  return ARMCC::NE;
1223   case ISD::SETEQ:  return ARMCC::EQ;
1224   case ISD::SETGT:  return ARMCC::GT;
1225   case ISD::SETGE:  return ARMCC::GE;
1226   case ISD::SETLT:  return ARMCC::LT;
1227   case ISD::SETLE:  return ARMCC::LE;
1228   case ISD::SETUGT: return ARMCC::HI;
1229   case ISD::SETUGE: return ARMCC::HS;
1230   case ISD::SETULT: return ARMCC::LO;
1231   case ISD::SETULE: return ARMCC::LS;
1232   }
1233 }
1234
1235 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1236 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1237                         ARMCC::CondCodes &CondCode2) {
1238   CondCode2 = ARMCC::AL;
1239   switch (CC) {
1240   default: llvm_unreachable("Unknown FP condition!");
1241   case ISD::SETEQ:
1242   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1243   case ISD::SETGT:
1244   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1245   case ISD::SETGE:
1246   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1247   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1248   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1249   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1250   case ISD::SETO:   CondCode = ARMCC::VC; break;
1251   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1252   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1253   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1254   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1255   case ISD::SETLT:
1256   case ISD::SETULT: CondCode = ARMCC::LT; break;
1257   case ISD::SETLE:
1258   case ISD::SETULE: CondCode = ARMCC::LE; break;
1259   case ISD::SETNE:
1260   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1261   }
1262 }
1263
1264 //===----------------------------------------------------------------------===//
1265 //                      Calling Convention Implementation
1266 //===----------------------------------------------------------------------===//
1267
1268 #include "ARMGenCallingConv.inc"
1269
1270 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1271 /// account presence of floating point hardware and calling convention
1272 /// limitations, such as support for variadic functions.
1273 CallingConv::ID
1274 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1275                                            bool isVarArg) const {
1276   switch (CC) {
1277   default:
1278     llvm_unreachable("Unsupported calling convention");
1279   case CallingConv::ARM_AAPCS:
1280   case CallingConv::ARM_APCS:
1281   case CallingConv::GHC:
1282     return CC;
1283   case CallingConv::ARM_AAPCS_VFP:
1284     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1285   case CallingConv::C:
1286     if (!Subtarget->isAAPCS_ABI())
1287       return CallingConv::ARM_APCS;
1288     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1289              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1290              !isVarArg)
1291       return CallingConv::ARM_AAPCS_VFP;
1292     else
1293       return CallingConv::ARM_AAPCS;
1294   case CallingConv::Fast:
1295     if (!Subtarget->isAAPCS_ABI()) {
1296       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1297         return CallingConv::Fast;
1298       return CallingConv::ARM_APCS;
1299     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1300       return CallingConv::ARM_AAPCS_VFP;
1301     else
1302       return CallingConv::ARM_AAPCS;
1303   }
1304 }
1305
1306 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1307 /// CallingConvention.
1308 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1309                                                  bool Return,
1310                                                  bool isVarArg) const {
1311   switch (getEffectiveCallingConv(CC, isVarArg)) {
1312   default:
1313     llvm_unreachable("Unsupported calling convention");
1314   case CallingConv::ARM_APCS:
1315     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1316   case CallingConv::ARM_AAPCS:
1317     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1318   case CallingConv::ARM_AAPCS_VFP:
1319     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1320   case CallingConv::Fast:
1321     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1322   case CallingConv::GHC:
1323     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1324   }
1325 }
1326
1327 /// LowerCallResult - Lower the result values of a call into the
1328 /// appropriate copies out of appropriate physical registers.
1329 SDValue
1330 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1331                                    CallingConv::ID CallConv, bool isVarArg,
1332                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1333                                    SDLoc dl, SelectionDAG &DAG,
1334                                    SmallVectorImpl<SDValue> &InVals,
1335                                    bool isThisReturn, SDValue ThisVal) const {
1336
1337   // Assign locations to each value returned by this call.
1338   SmallVector<CCValAssign, 16> RVLocs;
1339   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1340                     *DAG.getContext(), Call);
1341   CCInfo.AnalyzeCallResult(Ins,
1342                            CCAssignFnForNode(CallConv, /* Return*/ true,
1343                                              isVarArg));
1344
1345   // Copy all of the result registers out of their specified physreg.
1346   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1347     CCValAssign VA = RVLocs[i];
1348
1349     // Pass 'this' value directly from the argument to return value, to avoid
1350     // reg unit interference
1351     if (i == 0 && isThisReturn) {
1352       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1353              "unexpected return calling convention register assignment");
1354       InVals.push_back(ThisVal);
1355       continue;
1356     }
1357
1358     SDValue Val;
1359     if (VA.needsCustom()) {
1360       // Handle f64 or half of a v2f64.
1361       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1362                                       InFlag);
1363       Chain = Lo.getValue(1);
1364       InFlag = Lo.getValue(2);
1365       VA = RVLocs[++i]; // skip ahead to next loc
1366       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1367                                       InFlag);
1368       Chain = Hi.getValue(1);
1369       InFlag = Hi.getValue(2);
1370       if (!Subtarget->isLittle())
1371         std::swap (Lo, Hi);
1372       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1373
1374       if (VA.getLocVT() == MVT::v2f64) {
1375         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1376         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1377                           DAG.getConstant(0, MVT::i32));
1378
1379         VA = RVLocs[++i]; // skip ahead to next loc
1380         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1381         Chain = Lo.getValue(1);
1382         InFlag = Lo.getValue(2);
1383         VA = RVLocs[++i]; // skip ahead to next loc
1384         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1385         Chain = Hi.getValue(1);
1386         InFlag = Hi.getValue(2);
1387         if (!Subtarget->isLittle())
1388           std::swap (Lo, Hi);
1389         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1390         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1391                           DAG.getConstant(1, MVT::i32));
1392       }
1393     } else {
1394       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1395                                InFlag);
1396       Chain = Val.getValue(1);
1397       InFlag = Val.getValue(2);
1398     }
1399
1400     switch (VA.getLocInfo()) {
1401     default: llvm_unreachable("Unknown loc info!");
1402     case CCValAssign::Full: break;
1403     case CCValAssign::BCvt:
1404       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1405       break;
1406     }
1407
1408     InVals.push_back(Val);
1409   }
1410
1411   return Chain;
1412 }
1413
1414 /// LowerMemOpCallTo - Store the argument to the stack.
1415 SDValue
1416 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1417                                     SDValue StackPtr, SDValue Arg,
1418                                     SDLoc dl, SelectionDAG &DAG,
1419                                     const CCValAssign &VA,
1420                                     ISD::ArgFlagsTy Flags) const {
1421   unsigned LocMemOffset = VA.getLocMemOffset();
1422   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1423   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1424   return DAG.getStore(Chain, dl, Arg, PtrOff,
1425                       MachinePointerInfo::getStack(LocMemOffset),
1426                       false, false, 0);
1427 }
1428
1429 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1430                                          SDValue Chain, SDValue &Arg,
1431                                          RegsToPassVector &RegsToPass,
1432                                          CCValAssign &VA, CCValAssign &NextVA,
1433                                          SDValue &StackPtr,
1434                                          SmallVectorImpl<SDValue> &MemOpChains,
1435                                          ISD::ArgFlagsTy Flags) const {
1436
1437   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1438                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1439   unsigned id = Subtarget->isLittle() ? 0 : 1;
1440   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1441
1442   if (NextVA.isRegLoc())
1443     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1444   else {
1445     assert(NextVA.isMemLoc());
1446     if (!StackPtr.getNode())
1447       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1448
1449     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1450                                            dl, DAG, NextVA,
1451                                            Flags));
1452   }
1453 }
1454
1455 /// LowerCall - Lowering a call into a callseq_start <-
1456 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1457 /// nodes.
1458 SDValue
1459 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1460                              SmallVectorImpl<SDValue> &InVals) const {
1461   SelectionDAG &DAG                     = CLI.DAG;
1462   SDLoc &dl                          = CLI.DL;
1463   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1464   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1465   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1466   SDValue Chain                         = CLI.Chain;
1467   SDValue Callee                        = CLI.Callee;
1468   bool &isTailCall                      = CLI.IsTailCall;
1469   CallingConv::ID CallConv              = CLI.CallConv;
1470   bool doesNotRet                       = CLI.DoesNotReturn;
1471   bool isVarArg                         = CLI.IsVarArg;
1472
1473   MachineFunction &MF = DAG.getMachineFunction();
1474   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1475   bool isThisReturn   = false;
1476   bool isSibCall      = false;
1477
1478   // Disable tail calls if they're not supported.
1479   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1480     isTailCall = false;
1481
1482   if (isTailCall) {
1483     // Check if it's really possible to do a tail call.
1484     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1485                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1486                                                    Outs, OutVals, Ins, DAG);
1487     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1488       report_fatal_error("failed to perform tail call elimination on a call "
1489                          "site marked musttail");
1490     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1491     // detected sibcalls.
1492     if (isTailCall) {
1493       ++NumTailCalls;
1494       isSibCall = true;
1495     }
1496   }
1497
1498   // Analyze operands of the call, assigning locations to each operand.
1499   SmallVector<CCValAssign, 16> ArgLocs;
1500   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1501                     *DAG.getContext(), Call);
1502   CCInfo.AnalyzeCallOperands(Outs,
1503                              CCAssignFnForNode(CallConv, /* Return*/ false,
1504                                                isVarArg));
1505
1506   // Get a count of how many bytes are to be pushed on the stack.
1507   unsigned NumBytes = CCInfo.getNextStackOffset();
1508
1509   // For tail calls, memory operands are available in our caller's stack.
1510   if (isSibCall)
1511     NumBytes = 0;
1512
1513   // Adjust the stack pointer for the new arguments...
1514   // These operations are automatically eliminated by the prolog/epilog pass
1515   if (!isSibCall)
1516     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1517                                  dl);
1518
1519   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1520
1521   RegsToPassVector RegsToPass;
1522   SmallVector<SDValue, 8> MemOpChains;
1523
1524   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1525   // of tail call optimization, arguments are handled later.
1526   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1527        i != e;
1528        ++i, ++realArgIdx) {
1529     CCValAssign &VA = ArgLocs[i];
1530     SDValue Arg = OutVals[realArgIdx];
1531     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1532     bool isByVal = Flags.isByVal();
1533
1534     // Promote the value if needed.
1535     switch (VA.getLocInfo()) {
1536     default: llvm_unreachable("Unknown loc info!");
1537     case CCValAssign::Full: break;
1538     case CCValAssign::SExt:
1539       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1540       break;
1541     case CCValAssign::ZExt:
1542       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1543       break;
1544     case CCValAssign::AExt:
1545       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1546       break;
1547     case CCValAssign::BCvt:
1548       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1549       break;
1550     }
1551
1552     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1553     if (VA.needsCustom()) {
1554       if (VA.getLocVT() == MVT::v2f64) {
1555         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1556                                   DAG.getConstant(0, MVT::i32));
1557         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1558                                   DAG.getConstant(1, MVT::i32));
1559
1560         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1561                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1562
1563         VA = ArgLocs[++i]; // skip ahead to next loc
1564         if (VA.isRegLoc()) {
1565           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1566                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1567         } else {
1568           assert(VA.isMemLoc());
1569
1570           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1571                                                  dl, DAG, VA, Flags));
1572         }
1573       } else {
1574         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1575                          StackPtr, MemOpChains, Flags);
1576       }
1577     } else if (VA.isRegLoc()) {
1578       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1579         assert(VA.getLocVT() == MVT::i32 &&
1580                "unexpected calling convention register assignment");
1581         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1582                "unexpected use of 'returned'");
1583         isThisReturn = true;
1584       }
1585       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1586     } else if (isByVal) {
1587       assert(VA.isMemLoc());
1588       unsigned offset = 0;
1589
1590       // True if this byval aggregate will be split between registers
1591       // and memory.
1592       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1593       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1594
1595       if (CurByValIdx < ByValArgsCount) {
1596
1597         unsigned RegBegin, RegEnd;
1598         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1599
1600         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1601         unsigned int i, j;
1602         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1603           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1604           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1605           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1606                                      MachinePointerInfo(),
1607                                      false, false, false,
1608                                      DAG.InferPtrAlignment(AddArg));
1609           MemOpChains.push_back(Load.getValue(1));
1610           RegsToPass.push_back(std::make_pair(j, Load));
1611         }
1612
1613         // If parameter size outsides register area, "offset" value
1614         // helps us to calculate stack slot for remained part properly.
1615         offset = RegEnd - RegBegin;
1616
1617         CCInfo.nextInRegsParam();
1618       }
1619
1620       if (Flags.getByValSize() > 4*offset) {
1621         unsigned LocMemOffset = VA.getLocMemOffset();
1622         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1623         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1624                                   StkPtrOff);
1625         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1626         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1627         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1628                                            MVT::i32);
1629         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1630
1631         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1632         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1633         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1634                                           Ops));
1635       }
1636     } else if (!isSibCall) {
1637       assert(VA.isMemLoc());
1638
1639       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1640                                              dl, DAG, VA, Flags));
1641     }
1642   }
1643
1644   if (!MemOpChains.empty())
1645     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1646
1647   // Build a sequence of copy-to-reg nodes chained together with token chain
1648   // and flag operands which copy the outgoing args into the appropriate regs.
1649   SDValue InFlag;
1650   // Tail call byval lowering might overwrite argument registers so in case of
1651   // tail call optimization the copies to registers are lowered later.
1652   if (!isTailCall)
1653     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1654       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1655                                RegsToPass[i].second, InFlag);
1656       InFlag = Chain.getValue(1);
1657     }
1658
1659   // For tail calls lower the arguments to the 'real' stack slot.
1660   if (isTailCall) {
1661     // Force all the incoming stack arguments to be loaded from the stack
1662     // before any new outgoing arguments are stored to the stack, because the
1663     // outgoing stack slots may alias the incoming argument stack slots, and
1664     // the alias isn't otherwise explicit. This is slightly more conservative
1665     // than necessary, because it means that each store effectively depends
1666     // on every argument instead of just those arguments it would clobber.
1667
1668     // Do not flag preceding copytoreg stuff together with the following stuff.
1669     InFlag = SDValue();
1670     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1671       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1672                                RegsToPass[i].second, InFlag);
1673       InFlag = Chain.getValue(1);
1674     }
1675     InFlag = SDValue();
1676   }
1677
1678   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1679   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1680   // node so that legalize doesn't hack it.
1681   bool isDirect = false;
1682   bool isARMFunc = false;
1683   bool isLocalARMFunc = false;
1684   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1685
1686   if (EnableARMLongCalls) {
1687     assert((Subtarget->isTargetWindows() ||
1688             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1689            "long-calls with non-static relocation model!");
1690     // Handle a global address or an external symbol. If it's not one of
1691     // those, the target's already in a register, so we don't need to do
1692     // anything extra.
1693     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1694       const GlobalValue *GV = G->getGlobal();
1695       // Create a constant pool entry for the callee address
1696       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1697       ARMConstantPoolValue *CPV =
1698         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1699
1700       // Get the address of the callee into a register
1701       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1702       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1703       Callee = DAG.getLoad(getPointerTy(), dl,
1704                            DAG.getEntryNode(), CPAddr,
1705                            MachinePointerInfo::getConstantPool(),
1706                            false, false, false, 0);
1707     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1708       const char *Sym = S->getSymbol();
1709
1710       // Create a constant pool entry for the callee address
1711       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1712       ARMConstantPoolValue *CPV =
1713         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1714                                       ARMPCLabelIndex, 0);
1715       // Get the address of the callee into a register
1716       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1717       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1718       Callee = DAG.getLoad(getPointerTy(), dl,
1719                            DAG.getEntryNode(), CPAddr,
1720                            MachinePointerInfo::getConstantPool(),
1721                            false, false, false, 0);
1722     }
1723   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1724     const GlobalValue *GV = G->getGlobal();
1725     isDirect = true;
1726     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1727     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1728                    getTargetMachine().getRelocationModel() != Reloc::Static;
1729     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1730     // ARM call to a local ARM function is predicable.
1731     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1732     // tBX takes a register source operand.
1733     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1734       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1735       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1736                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1737                                                       0, ARMII::MO_NONLAZY));
1738       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1739                            MachinePointerInfo::getGOT(), false, false, true, 0);
1740     } else if (Subtarget->isTargetCOFF()) {
1741       assert(Subtarget->isTargetWindows() &&
1742              "Windows is the only supported COFF target");
1743       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1744                                  ? ARMII::MO_DLLIMPORT
1745                                  : ARMII::MO_NO_FLAG;
1746       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1747                                           TargetFlags);
1748       if (GV->hasDLLImportStorageClass())
1749         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1750                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1751                                          Callee), MachinePointerInfo::getGOT(),
1752                              false, false, false, 0);
1753     } else {
1754       // On ELF targets for PIC code, direct calls should go through the PLT
1755       unsigned OpFlags = 0;
1756       if (Subtarget->isTargetELF() &&
1757           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1758         OpFlags = ARMII::MO_PLT;
1759       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1760     }
1761   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1762     isDirect = true;
1763     bool isStub = Subtarget->isTargetMachO() &&
1764                   getTargetMachine().getRelocationModel() != Reloc::Static;
1765     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1766     // tBX takes a register source operand.
1767     const char *Sym = S->getSymbol();
1768     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1769       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1770       ARMConstantPoolValue *CPV =
1771         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1772                                       ARMPCLabelIndex, 4);
1773       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1774       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1775       Callee = DAG.getLoad(getPointerTy(), dl,
1776                            DAG.getEntryNode(), CPAddr,
1777                            MachinePointerInfo::getConstantPool(),
1778                            false, false, false, 0);
1779       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1780       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1781                            getPointerTy(), Callee, PICLabel);
1782     } else {
1783       unsigned OpFlags = 0;
1784       // On ELF targets for PIC code, direct calls should go through the PLT
1785       if (Subtarget->isTargetELF() &&
1786                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1787         OpFlags = ARMII::MO_PLT;
1788       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1789     }
1790   }
1791
1792   // FIXME: handle tail calls differently.
1793   unsigned CallOpc;
1794   bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1795       AttributeSet::FunctionIndex, Attribute::MinSize);
1796   if (Subtarget->isThumb()) {
1797     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1798       CallOpc = ARMISD::CALL_NOLINK;
1799     else
1800       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1801   } else {
1802     if (!isDirect && !Subtarget->hasV5TOps())
1803       CallOpc = ARMISD::CALL_NOLINK;
1804     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1805                // Emit regular call when code size is the priority
1806                !HasMinSizeAttr)
1807       // "mov lr, pc; b _foo" to avoid confusing the RSP
1808       CallOpc = ARMISD::CALL_NOLINK;
1809     else
1810       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1811   }
1812
1813   std::vector<SDValue> Ops;
1814   Ops.push_back(Chain);
1815   Ops.push_back(Callee);
1816
1817   // Add argument registers to the end of the list so that they are known live
1818   // into the call.
1819   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1820     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1821                                   RegsToPass[i].second.getValueType()));
1822
1823   // Add a register mask operand representing the call-preserved registers.
1824   if (!isTailCall) {
1825     const uint32_t *Mask;
1826     const TargetRegisterInfo *TRI =
1827         getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1828     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1829     if (isThisReturn) {
1830       // For 'this' returns, use the R0-preserving mask if applicable
1831       Mask = ARI->getThisReturnPreservedMask(CallConv);
1832       if (!Mask) {
1833         // Set isThisReturn to false if the calling convention is not one that
1834         // allows 'returned' to be modeled in this way, so LowerCallResult does
1835         // not try to pass 'this' straight through
1836         isThisReturn = false;
1837         Mask = ARI->getCallPreservedMask(CallConv);
1838       }
1839     } else
1840       Mask = ARI->getCallPreservedMask(CallConv);
1841
1842     assert(Mask && "Missing call preserved mask for calling convention");
1843     Ops.push_back(DAG.getRegisterMask(Mask));
1844   }
1845
1846   if (InFlag.getNode())
1847     Ops.push_back(InFlag);
1848
1849   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1850   if (isTailCall)
1851     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1852
1853   // Returns a chain and a flag for retval copy to use.
1854   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1855   InFlag = Chain.getValue(1);
1856
1857   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1858                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1859   if (!Ins.empty())
1860     InFlag = Chain.getValue(1);
1861
1862   // Handle result values, copying them out of physregs into vregs that we
1863   // return.
1864   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1865                          InVals, isThisReturn,
1866                          isThisReturn ? OutVals[0] : SDValue());
1867 }
1868
1869 /// HandleByVal - Every parameter *after* a byval parameter is passed
1870 /// on the stack.  Remember the next parameter register to allocate,
1871 /// and then confiscate the rest of the parameter registers to insure
1872 /// this.
1873 void
1874 ARMTargetLowering::HandleByVal(
1875     CCState *State, unsigned &size, unsigned Align) const {
1876   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1877   assert((State->getCallOrPrologue() == Prologue ||
1878           State->getCallOrPrologue() == Call) &&
1879          "unhandled ParmContext");
1880
1881   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1882     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1883       unsigned AlignInRegs = Align / 4;
1884       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1885       for (unsigned i = 0; i < Waste; ++i)
1886         reg = State->AllocateReg(GPRArgRegs, 4);
1887     }
1888     if (reg != 0) {
1889       unsigned excess = 4 * (ARM::R4 - reg);
1890
1891       // Special case when NSAA != SP and parameter size greater than size of
1892       // all remained GPR regs. In that case we can't split parameter, we must
1893       // send it to stack. We also must set NCRN to R4, so waste all
1894       // remained registers.
1895       const unsigned NSAAOffset = State->getNextStackOffset();
1896       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1897         while (State->AllocateReg(GPRArgRegs, 4))
1898           ;
1899         return;
1900       }
1901
1902       // First register for byval parameter is the first register that wasn't
1903       // allocated before this method call, so it would be "reg".
1904       // If parameter is small enough to be saved in range [reg, r4), then
1905       // the end (first after last) register would be reg + param-size-in-regs,
1906       // else parameter would be splitted between registers and stack,
1907       // end register would be r4 in this case.
1908       unsigned ByValRegBegin = reg;
1909       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1910       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1911       // Note, first register is allocated in the beginning of function already,
1912       // allocate remained amount of registers we need.
1913       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1914         State->AllocateReg(GPRArgRegs, 4);
1915       // A byval parameter that is split between registers and memory needs its
1916       // size truncated here.
1917       // In the case where the entire structure fits in registers, we set the
1918       // size in memory to zero.
1919       if (size < excess)
1920         size = 0;
1921       else
1922         size -= excess;
1923     }
1924   }
1925 }
1926
1927 /// MatchingStackOffset - Return true if the given stack call argument is
1928 /// already available in the same position (relatively) of the caller's
1929 /// incoming argument stack.
1930 static
1931 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1932                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1933                          const TargetInstrInfo *TII) {
1934   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1935   int FI = INT_MAX;
1936   if (Arg.getOpcode() == ISD::CopyFromReg) {
1937     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1938     if (!TargetRegisterInfo::isVirtualRegister(VR))
1939       return false;
1940     MachineInstr *Def = MRI->getVRegDef(VR);
1941     if (!Def)
1942       return false;
1943     if (!Flags.isByVal()) {
1944       if (!TII->isLoadFromStackSlot(Def, FI))
1945         return false;
1946     } else {
1947       return false;
1948     }
1949   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1950     if (Flags.isByVal())
1951       // ByVal argument is passed in as a pointer but it's now being
1952       // dereferenced. e.g.
1953       // define @foo(%struct.X* %A) {
1954       //   tail call @bar(%struct.X* byval %A)
1955       // }
1956       return false;
1957     SDValue Ptr = Ld->getBasePtr();
1958     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1959     if (!FINode)
1960       return false;
1961     FI = FINode->getIndex();
1962   } else
1963     return false;
1964
1965   assert(FI != INT_MAX);
1966   if (!MFI->isFixedObjectIndex(FI))
1967     return false;
1968   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1969 }
1970
1971 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1972 /// for tail call optimization. Targets which want to do tail call
1973 /// optimization should implement this function.
1974 bool
1975 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1976                                                      CallingConv::ID CalleeCC,
1977                                                      bool isVarArg,
1978                                                      bool isCalleeStructRet,
1979                                                      bool isCallerStructRet,
1980                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1981                                     const SmallVectorImpl<SDValue> &OutVals,
1982                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1983                                                      SelectionDAG& DAG) const {
1984   const Function *CallerF = DAG.getMachineFunction().getFunction();
1985   CallingConv::ID CallerCC = CallerF->getCallingConv();
1986   bool CCMatch = CallerCC == CalleeCC;
1987
1988   // Look for obvious safe cases to perform tail call optimization that do not
1989   // require ABI changes. This is what gcc calls sibcall.
1990
1991   // Do not sibcall optimize vararg calls unless the call site is not passing
1992   // any arguments.
1993   if (isVarArg && !Outs.empty())
1994     return false;
1995
1996   // Exception-handling functions need a special set of instructions to indicate
1997   // a return to the hardware. Tail-calling another function would probably
1998   // break this.
1999   if (CallerF->hasFnAttribute("interrupt"))
2000     return false;
2001
2002   // Also avoid sibcall optimization if either caller or callee uses struct
2003   // return semantics.
2004   if (isCalleeStructRet || isCallerStructRet)
2005     return false;
2006
2007   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
2008   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2009   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2010   // support in the assembler and linker to be used. This would need to be
2011   // fixed to fully support tail calls in Thumb1.
2012   //
2013   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2014   // LR.  This means if we need to reload LR, it takes an extra instructions,
2015   // which outweighs the value of the tail call; but here we don't know yet
2016   // whether LR is going to be used.  Probably the right approach is to
2017   // generate the tail call here and turn it back into CALL/RET in
2018   // emitEpilogue if LR is used.
2019
2020   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2021   // but we need to make sure there are enough registers; the only valid
2022   // registers are the 4 used for parameters.  We don't currently do this
2023   // case.
2024   if (Subtarget->isThumb1Only())
2025     return false;
2026
2027   // Externally-defined functions with weak linkage should not be
2028   // tail-called on ARM when the OS does not support dynamic
2029   // pre-emption of symbols, as the AAELF spec requires normal calls
2030   // to undefined weak functions to be replaced with a NOP or jump to the
2031   // next instruction. The behaviour of branch instructions in this
2032   // situation (as used for tail calls) is implementation-defined, so we
2033   // cannot rely on the linker replacing the tail call with a return.
2034   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2035     const GlobalValue *GV = G->getGlobal();
2036     if (GV->hasExternalWeakLinkage())
2037       return false;
2038   }
2039
2040   // If the calling conventions do not match, then we'd better make sure the
2041   // results are returned in the same way as what the caller expects.
2042   if (!CCMatch) {
2043     SmallVector<CCValAssign, 16> RVLocs1;
2044     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2045                        *DAG.getContext(), Call);
2046     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2047
2048     SmallVector<CCValAssign, 16> RVLocs2;
2049     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2050                        *DAG.getContext(), Call);
2051     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2052
2053     if (RVLocs1.size() != RVLocs2.size())
2054       return false;
2055     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2056       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2057         return false;
2058       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2059         return false;
2060       if (RVLocs1[i].isRegLoc()) {
2061         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2062           return false;
2063       } else {
2064         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2065           return false;
2066       }
2067     }
2068   }
2069
2070   // If Caller's vararg or byval argument has been split between registers and
2071   // stack, do not perform tail call, since part of the argument is in caller's
2072   // local frame.
2073   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2074                                       getInfo<ARMFunctionInfo>();
2075   if (AFI_Caller->getArgRegsSaveSize())
2076     return false;
2077
2078   // If the callee takes no arguments then go on to check the results of the
2079   // call.
2080   if (!Outs.empty()) {
2081     // Check if stack adjustment is needed. For now, do not do this if any
2082     // argument is passed on the stack.
2083     SmallVector<CCValAssign, 16> ArgLocs;
2084     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2085                       *DAG.getContext(), Call);
2086     CCInfo.AnalyzeCallOperands(Outs,
2087                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2088     if (CCInfo.getNextStackOffset()) {
2089       MachineFunction &MF = DAG.getMachineFunction();
2090
2091       // Check if the arguments are already laid out in the right way as
2092       // the caller's fixed stack objects.
2093       MachineFrameInfo *MFI = MF.getFrameInfo();
2094       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2095       const TargetInstrInfo *TII =
2096           getTargetMachine().getSubtargetImpl()->getInstrInfo();
2097       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2098            i != e;
2099            ++i, ++realArgIdx) {
2100         CCValAssign &VA = ArgLocs[i];
2101         EVT RegVT = VA.getLocVT();
2102         SDValue Arg = OutVals[realArgIdx];
2103         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2104         if (VA.getLocInfo() == CCValAssign::Indirect)
2105           return false;
2106         if (VA.needsCustom()) {
2107           // f64 and vector types are split into multiple registers or
2108           // register/stack-slot combinations.  The types will not match
2109           // the registers; give up on memory f64 refs until we figure
2110           // out what to do about this.
2111           if (!VA.isRegLoc())
2112             return false;
2113           if (!ArgLocs[++i].isRegLoc())
2114             return false;
2115           if (RegVT == MVT::v2f64) {
2116             if (!ArgLocs[++i].isRegLoc())
2117               return false;
2118             if (!ArgLocs[++i].isRegLoc())
2119               return false;
2120           }
2121         } else if (!VA.isRegLoc()) {
2122           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2123                                    MFI, MRI, TII))
2124             return false;
2125         }
2126       }
2127     }
2128   }
2129
2130   return true;
2131 }
2132
2133 bool
2134 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2135                                   MachineFunction &MF, bool isVarArg,
2136                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2137                                   LLVMContext &Context) const {
2138   SmallVector<CCValAssign, 16> RVLocs;
2139   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2140   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2141                                                     isVarArg));
2142 }
2143
2144 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2145                                     SDLoc DL, SelectionDAG &DAG) {
2146   const MachineFunction &MF = DAG.getMachineFunction();
2147   const Function *F = MF.getFunction();
2148
2149   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2150
2151   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2152   // version of the "preferred return address". These offsets affect the return
2153   // instruction if this is a return from PL1 without hypervisor extensions.
2154   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2155   //    SWI:     0      "subs pc, lr, #0"
2156   //    ABORT:   +4     "subs pc, lr, #4"
2157   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2158   // UNDEF varies depending on where the exception came from ARM or Thumb
2159   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2160
2161   int64_t LROffset;
2162   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2163       IntKind == "ABORT")
2164     LROffset = 4;
2165   else if (IntKind == "SWI" || IntKind == "UNDEF")
2166     LROffset = 0;
2167   else
2168     report_fatal_error("Unsupported interrupt attribute. If present, value "
2169                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2170
2171   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2172
2173   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2174 }
2175
2176 SDValue
2177 ARMTargetLowering::LowerReturn(SDValue Chain,
2178                                CallingConv::ID CallConv, bool isVarArg,
2179                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2180                                const SmallVectorImpl<SDValue> &OutVals,
2181                                SDLoc dl, SelectionDAG &DAG) const {
2182
2183   // CCValAssign - represent the assignment of the return value to a location.
2184   SmallVector<CCValAssign, 16> RVLocs;
2185
2186   // CCState - Info about the registers and stack slots.
2187   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2188                     *DAG.getContext(), Call);
2189
2190   // Analyze outgoing return values.
2191   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2192                                                isVarArg));
2193
2194   SDValue Flag;
2195   SmallVector<SDValue, 4> RetOps;
2196   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2197   bool isLittleEndian = Subtarget->isLittle();
2198
2199   MachineFunction &MF = DAG.getMachineFunction();
2200   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2201   AFI->setReturnRegsCount(RVLocs.size());
2202
2203   // Copy the result values into the output registers.
2204   for (unsigned i = 0, realRVLocIdx = 0;
2205        i != RVLocs.size();
2206        ++i, ++realRVLocIdx) {
2207     CCValAssign &VA = RVLocs[i];
2208     assert(VA.isRegLoc() && "Can only return in registers!");
2209
2210     SDValue Arg = OutVals[realRVLocIdx];
2211
2212     switch (VA.getLocInfo()) {
2213     default: llvm_unreachable("Unknown loc info!");
2214     case CCValAssign::Full: break;
2215     case CCValAssign::BCvt:
2216       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2217       break;
2218     }
2219
2220     if (VA.needsCustom()) {
2221       if (VA.getLocVT() == MVT::v2f64) {
2222         // Extract the first half and return it in two registers.
2223         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2224                                    DAG.getConstant(0, MVT::i32));
2225         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2226                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2227
2228         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2229                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2230                                  Flag);
2231         Flag = Chain.getValue(1);
2232         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2233         VA = RVLocs[++i]; // skip ahead to next loc
2234         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2235                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2236                                  Flag);
2237         Flag = Chain.getValue(1);
2238         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2239         VA = RVLocs[++i]; // skip ahead to next loc
2240
2241         // Extract the 2nd half and fall through to handle it as an f64 value.
2242         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2243                           DAG.getConstant(1, MVT::i32));
2244       }
2245       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2246       // available.
2247       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2248                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2249       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2250                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2251                                Flag);
2252       Flag = Chain.getValue(1);
2253       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2254       VA = RVLocs[++i]; // skip ahead to next loc
2255       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2256                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2257                                Flag);
2258     } else
2259       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2260
2261     // Guarantee that all emitted copies are
2262     // stuck together, avoiding something bad.
2263     Flag = Chain.getValue(1);
2264     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2265   }
2266
2267   // Update chain and glue.
2268   RetOps[0] = Chain;
2269   if (Flag.getNode())
2270     RetOps.push_back(Flag);
2271
2272   // CPUs which aren't M-class use a special sequence to return from
2273   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2274   // though we use "subs pc, lr, #N").
2275   //
2276   // M-class CPUs actually use a normal return sequence with a special
2277   // (hardware-provided) value in LR, so the normal code path works.
2278   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2279       !Subtarget->isMClass()) {
2280     if (Subtarget->isThumb1Only())
2281       report_fatal_error("interrupt attribute is not supported in Thumb1");
2282     return LowerInterruptReturn(RetOps, dl, DAG);
2283   }
2284
2285   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2286 }
2287
2288 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2289   if (N->getNumValues() != 1)
2290     return false;
2291   if (!N->hasNUsesOfValue(1, 0))
2292     return false;
2293
2294   SDValue TCChain = Chain;
2295   SDNode *Copy = *N->use_begin();
2296   if (Copy->getOpcode() == ISD::CopyToReg) {
2297     // If the copy has a glue operand, we conservatively assume it isn't safe to
2298     // perform a tail call.
2299     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2300       return false;
2301     TCChain = Copy->getOperand(0);
2302   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2303     SDNode *VMov = Copy;
2304     // f64 returned in a pair of GPRs.
2305     SmallPtrSet<SDNode*, 2> Copies;
2306     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2307          UI != UE; ++UI) {
2308       if (UI->getOpcode() != ISD::CopyToReg)
2309         return false;
2310       Copies.insert(*UI);
2311     }
2312     if (Copies.size() > 2)
2313       return false;
2314
2315     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2316          UI != UE; ++UI) {
2317       SDValue UseChain = UI->getOperand(0);
2318       if (Copies.count(UseChain.getNode()))
2319         // Second CopyToReg
2320         Copy = *UI;
2321       else {
2322         // We are at the top of this chain.
2323         // If the copy has a glue operand, we conservatively assume it
2324         // isn't safe to perform a tail call.
2325         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2326           return false;
2327         // First CopyToReg
2328         TCChain = UseChain;
2329       }
2330     }
2331   } else if (Copy->getOpcode() == ISD::BITCAST) {
2332     // f32 returned in a single GPR.
2333     if (!Copy->hasOneUse())
2334       return false;
2335     Copy = *Copy->use_begin();
2336     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2337       return false;
2338     // If the copy has a glue operand, we conservatively assume it isn't safe to
2339     // perform a tail call.
2340     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2341       return false;
2342     TCChain = Copy->getOperand(0);
2343   } else {
2344     return false;
2345   }
2346
2347   bool HasRet = false;
2348   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2349        UI != UE; ++UI) {
2350     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2351         UI->getOpcode() != ARMISD::INTRET_FLAG)
2352       return false;
2353     HasRet = true;
2354   }
2355
2356   if (!HasRet)
2357     return false;
2358
2359   Chain = TCChain;
2360   return true;
2361 }
2362
2363 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2364   if (!Subtarget->supportsTailCall())
2365     return false;
2366
2367   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2368     return false;
2369
2370   return !Subtarget->isThumb1Only();
2371 }
2372
2373 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2374 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2375 // one of the above mentioned nodes. It has to be wrapped because otherwise
2376 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2377 // be used to form addressing mode. These wrapped nodes will be selected
2378 // into MOVi.
2379 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2380   EVT PtrVT = Op.getValueType();
2381   // FIXME there is no actual debug info here
2382   SDLoc dl(Op);
2383   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2384   SDValue Res;
2385   if (CP->isMachineConstantPoolEntry())
2386     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2387                                     CP->getAlignment());
2388   else
2389     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2390                                     CP->getAlignment());
2391   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2392 }
2393
2394 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2395   return MachineJumpTableInfo::EK_Inline;
2396 }
2397
2398 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2399                                              SelectionDAG &DAG) const {
2400   MachineFunction &MF = DAG.getMachineFunction();
2401   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2402   unsigned ARMPCLabelIndex = 0;
2403   SDLoc DL(Op);
2404   EVT PtrVT = getPointerTy();
2405   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2406   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2407   SDValue CPAddr;
2408   if (RelocM == Reloc::Static) {
2409     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2410   } else {
2411     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2412     ARMPCLabelIndex = AFI->createPICLabelUId();
2413     ARMConstantPoolValue *CPV =
2414       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2415                                       ARMCP::CPBlockAddress, PCAdj);
2416     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2417   }
2418   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2419   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2420                                MachinePointerInfo::getConstantPool(),
2421                                false, false, false, 0);
2422   if (RelocM == Reloc::Static)
2423     return Result;
2424   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2425   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2426 }
2427
2428 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2429 SDValue
2430 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2431                                                  SelectionDAG &DAG) const {
2432   SDLoc dl(GA);
2433   EVT PtrVT = getPointerTy();
2434   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2435   MachineFunction &MF = DAG.getMachineFunction();
2436   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2437   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2438   ARMConstantPoolValue *CPV =
2439     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2440                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2441   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2442   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2443   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2444                          MachinePointerInfo::getConstantPool(),
2445                          false, false, false, 0);
2446   SDValue Chain = Argument.getValue(1);
2447
2448   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2449   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2450
2451   // call __tls_get_addr.
2452   ArgListTy Args;
2453   ArgListEntry Entry;
2454   Entry.Node = Argument;
2455   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2456   Args.push_back(Entry);
2457
2458   // FIXME: is there useful debug info available here?
2459   TargetLowering::CallLoweringInfo CLI(DAG);
2460   CLI.setDebugLoc(dl).setChain(Chain)
2461     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2462                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2463                0);
2464
2465   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2466   return CallResult.first;
2467 }
2468
2469 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2470 // "local exec" model.
2471 SDValue
2472 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2473                                         SelectionDAG &DAG,
2474                                         TLSModel::Model model) const {
2475   const GlobalValue *GV = GA->getGlobal();
2476   SDLoc dl(GA);
2477   SDValue Offset;
2478   SDValue Chain = DAG.getEntryNode();
2479   EVT PtrVT = getPointerTy();
2480   // Get the Thread Pointer
2481   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2482
2483   if (model == TLSModel::InitialExec) {
2484     MachineFunction &MF = DAG.getMachineFunction();
2485     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2486     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2487     // Initial exec model.
2488     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2489     ARMConstantPoolValue *CPV =
2490       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2491                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2492                                       true);
2493     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2494     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2495     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2496                          MachinePointerInfo::getConstantPool(),
2497                          false, false, false, 0);
2498     Chain = Offset.getValue(1);
2499
2500     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2501     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2502
2503     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2504                          MachinePointerInfo::getConstantPool(),
2505                          false, false, false, 0);
2506   } else {
2507     // local exec model
2508     assert(model == TLSModel::LocalExec);
2509     ARMConstantPoolValue *CPV =
2510       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2511     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2512     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2513     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2514                          MachinePointerInfo::getConstantPool(),
2515                          false, false, false, 0);
2516   }
2517
2518   // The address of the thread local variable is the add of the thread
2519   // pointer with the offset of the variable.
2520   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2521 }
2522
2523 SDValue
2524 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2525   // TODO: implement the "local dynamic" model
2526   assert(Subtarget->isTargetELF() &&
2527          "TLS not implemented for non-ELF targets");
2528   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2529
2530   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2531
2532   switch (model) {
2533     case TLSModel::GeneralDynamic:
2534     case TLSModel::LocalDynamic:
2535       return LowerToTLSGeneralDynamicModel(GA, DAG);
2536     case TLSModel::InitialExec:
2537     case TLSModel::LocalExec:
2538       return LowerToTLSExecModels(GA, DAG, model);
2539   }
2540   llvm_unreachable("bogus TLS model");
2541 }
2542
2543 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2544                                                  SelectionDAG &DAG) const {
2545   EVT PtrVT = getPointerTy();
2546   SDLoc dl(Op);
2547   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2548   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2549     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2550     ARMConstantPoolValue *CPV =
2551       ARMConstantPoolConstant::Create(GV,
2552                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2553     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2554     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2555     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2556                                  CPAddr,
2557                                  MachinePointerInfo::getConstantPool(),
2558                                  false, false, false, 0);
2559     SDValue Chain = Result.getValue(1);
2560     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2561     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2562     if (!UseGOTOFF)
2563       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2564                            MachinePointerInfo::getGOT(),
2565                            false, false, false, 0);
2566     return Result;
2567   }
2568
2569   // If we have T2 ops, we can materialize the address directly via movt/movw
2570   // pair. This is always cheaper.
2571   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2572     ++NumMovwMovt;
2573     // FIXME: Once remat is capable of dealing with instructions with register
2574     // operands, expand this into two nodes.
2575     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2576                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2577   } else {
2578     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2579     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2580     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2581                        MachinePointerInfo::getConstantPool(),
2582                        false, false, false, 0);
2583   }
2584 }
2585
2586 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2587                                                     SelectionDAG &DAG) const {
2588   EVT PtrVT = getPointerTy();
2589   SDLoc dl(Op);
2590   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2591   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2592
2593   if (Subtarget->useMovt(DAG.getMachineFunction()))
2594     ++NumMovwMovt;
2595
2596   // FIXME: Once remat is capable of dealing with instructions with register
2597   // operands, expand this into multiple nodes
2598   unsigned Wrapper =
2599       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2600
2601   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2602   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2603
2604   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2605     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2606                          MachinePointerInfo::getGOT(), false, false, false, 0);
2607   return Result;
2608 }
2609
2610 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2611                                                      SelectionDAG &DAG) const {
2612   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2613   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2614          "Windows on ARM expects to use movw/movt");
2615
2616   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2617   const ARMII::TOF TargetFlags =
2618     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2619   EVT PtrVT = getPointerTy();
2620   SDValue Result;
2621   SDLoc DL(Op);
2622
2623   ++NumMovwMovt;
2624
2625   // FIXME: Once remat is capable of dealing with instructions with register
2626   // operands, expand this into two nodes.
2627   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2628                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2629                                                   TargetFlags));
2630   if (GV->hasDLLImportStorageClass())
2631     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2632                          MachinePointerInfo::getGOT(), false, false, false, 0);
2633   return Result;
2634 }
2635
2636 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2637                                                     SelectionDAG &DAG) const {
2638   assert(Subtarget->isTargetELF() &&
2639          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2640   MachineFunction &MF = DAG.getMachineFunction();
2641   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2642   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2643   EVT PtrVT = getPointerTy();
2644   SDLoc dl(Op);
2645   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2646   ARMConstantPoolValue *CPV =
2647     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2648                                   ARMPCLabelIndex, PCAdj);
2649   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2650   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2651   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2652                                MachinePointerInfo::getConstantPool(),
2653                                false, false, false, 0);
2654   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2655   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2656 }
2657
2658 SDValue
2659 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2660   SDLoc dl(Op);
2661   SDValue Val = DAG.getConstant(0, MVT::i32);
2662   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2663                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2664                      Op.getOperand(1), Val);
2665 }
2666
2667 SDValue
2668 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2669   SDLoc dl(Op);
2670   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2671                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2672 }
2673
2674 SDValue
2675 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2676                                           const ARMSubtarget *Subtarget) const {
2677   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2678   SDLoc dl(Op);
2679   switch (IntNo) {
2680   default: return SDValue();    // Don't custom lower most intrinsics.
2681   case Intrinsic::arm_rbit: {
2682     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2683            "RBIT intrinsic must have i32 type!");
2684     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2685   }
2686   case Intrinsic::arm_thread_pointer: {
2687     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2688     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2689   }
2690   case Intrinsic::eh_sjlj_lsda: {
2691     MachineFunction &MF = DAG.getMachineFunction();
2692     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2693     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2694     EVT PtrVT = getPointerTy();
2695     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2696     SDValue CPAddr;
2697     unsigned PCAdj = (RelocM != Reloc::PIC_)
2698       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2699     ARMConstantPoolValue *CPV =
2700       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2701                                       ARMCP::CPLSDA, PCAdj);
2702     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2703     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2704     SDValue Result =
2705       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2706                   MachinePointerInfo::getConstantPool(),
2707                   false, false, false, 0);
2708
2709     if (RelocM == Reloc::PIC_) {
2710       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2711       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2712     }
2713     return Result;
2714   }
2715   case Intrinsic::arm_neon_vmulls:
2716   case Intrinsic::arm_neon_vmullu: {
2717     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2718       ? ARMISD::VMULLs : ARMISD::VMULLu;
2719     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2720                        Op.getOperand(1), Op.getOperand(2));
2721   }
2722   }
2723 }
2724
2725 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2726                                  const ARMSubtarget *Subtarget) {
2727   // FIXME: handle "fence singlethread" more efficiently.
2728   SDLoc dl(Op);
2729   if (!Subtarget->hasDataBarrier()) {
2730     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2731     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2732     // here.
2733     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2734            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2735     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2736                        DAG.getConstant(0, MVT::i32));
2737   }
2738
2739   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2740   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2741   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2742   if (Subtarget->isMClass()) {
2743     // Only a full system barrier exists in the M-class architectures.
2744     Domain = ARM_MB::SY;
2745   } else if (Subtarget->isSwift() && Ord == Release) {
2746     // Swift happens to implement ISHST barriers in a way that's compatible with
2747     // Release semantics but weaker than ISH so we'd be fools not to use
2748     // it. Beware: other processors probably don't!
2749     Domain = ARM_MB::ISHST;
2750   }
2751
2752   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2753                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2754                      DAG.getConstant(Domain, MVT::i32));
2755 }
2756
2757 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2758                              const ARMSubtarget *Subtarget) {
2759   // ARM pre v5TE and Thumb1 does not have preload instructions.
2760   if (!(Subtarget->isThumb2() ||
2761         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2762     // Just preserve the chain.
2763     return Op.getOperand(0);
2764
2765   SDLoc dl(Op);
2766   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2767   if (!isRead &&
2768       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2769     // ARMv7 with MP extension has PLDW.
2770     return Op.getOperand(0);
2771
2772   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2773   if (Subtarget->isThumb()) {
2774     // Invert the bits.
2775     isRead = ~isRead & 1;
2776     isData = ~isData & 1;
2777   }
2778
2779   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2780                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2781                      DAG.getConstant(isData, MVT::i32));
2782 }
2783
2784 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2785   MachineFunction &MF = DAG.getMachineFunction();
2786   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2787
2788   // vastart just stores the address of the VarArgsFrameIndex slot into the
2789   // memory location argument.
2790   SDLoc dl(Op);
2791   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2792   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2793   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2794   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2795                       MachinePointerInfo(SV), false, false, 0);
2796 }
2797
2798 SDValue
2799 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2800                                         SDValue &Root, SelectionDAG &DAG,
2801                                         SDLoc dl) const {
2802   MachineFunction &MF = DAG.getMachineFunction();
2803   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2804
2805   const TargetRegisterClass *RC;
2806   if (AFI->isThumb1OnlyFunction())
2807     RC = &ARM::tGPRRegClass;
2808   else
2809     RC = &ARM::GPRRegClass;
2810
2811   // Transform the arguments stored in physical registers into virtual ones.
2812   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2813   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2814
2815   SDValue ArgValue2;
2816   if (NextVA.isMemLoc()) {
2817     MachineFrameInfo *MFI = MF.getFrameInfo();
2818     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2819
2820     // Create load node to retrieve arguments from the stack.
2821     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2822     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2823                             MachinePointerInfo::getFixedStack(FI),
2824                             false, false, false, 0);
2825   } else {
2826     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2827     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2828   }
2829   if (!Subtarget->isLittle())
2830     std::swap (ArgValue, ArgValue2);
2831   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2832 }
2833
2834 void
2835 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2836                                   unsigned InRegsParamRecordIdx,
2837                                   unsigned ArgSize,
2838                                   unsigned &ArgRegsSize,
2839                                   unsigned &ArgRegsSaveSize)
2840   const {
2841   unsigned NumGPRs;
2842   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2843     unsigned RBegin, REnd;
2844     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2845     NumGPRs = REnd - RBegin;
2846   } else {
2847     unsigned int firstUnalloced;
2848     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2849                                                 sizeof(GPRArgRegs) /
2850                                                 sizeof(GPRArgRegs[0]));
2851     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2852   }
2853
2854   unsigned Align = MF.getTarget()
2855                        .getSubtargetImpl()
2856                        ->getFrameLowering()
2857                        ->getStackAlignment();
2858   ArgRegsSize = NumGPRs * 4;
2859
2860   // If parameter is split between stack and GPRs...
2861   if (NumGPRs && Align > 4 &&
2862       (ArgRegsSize < ArgSize ||
2863         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2864     // Add padding for part of param recovered from GPRs.  For example,
2865     // if Align == 8, its last byte must be at address K*8 - 1.
2866     // We need to do it, since remained (stack) part of parameter has
2867     // stack alignment, and we need to "attach" "GPRs head" without gaps
2868     // to it:
2869     // Stack:
2870     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2871     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2872     //
2873     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2874     unsigned Padding =
2875         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2876     ArgRegsSaveSize = ArgRegsSize + Padding;
2877   } else
2878     // We don't need to extend regs save size for byval parameters if they
2879     // are passed via GPRs only.
2880     ArgRegsSaveSize = ArgRegsSize;
2881 }
2882
2883 // The remaining GPRs hold either the beginning of variable-argument
2884 // data, or the beginning of an aggregate passed by value (usually
2885 // byval).  Either way, we allocate stack slots adjacent to the data
2886 // provided by our caller, and store the unallocated registers there.
2887 // If this is a variadic function, the va_list pointer will begin with
2888 // these values; otherwise, this reassembles a (byval) structure that
2889 // was split between registers and memory.
2890 // Return: The frame index registers were stored into.
2891 int
2892 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2893                                   SDLoc dl, SDValue &Chain,
2894                                   const Value *OrigArg,
2895                                   unsigned InRegsParamRecordIdx,
2896                                   unsigned OffsetFromOrigArg,
2897                                   unsigned ArgOffset,
2898                                   unsigned ArgSize,
2899                                   bool ForceMutable,
2900                                   unsigned ByValStoreOffset,
2901                                   unsigned TotalArgRegsSaveSize) const {
2902
2903   // Currently, two use-cases possible:
2904   // Case #1. Non-var-args function, and we meet first byval parameter.
2905   //          Setup first unallocated register as first byval register;
2906   //          eat all remained registers
2907   //          (these two actions are performed by HandleByVal method).
2908   //          Then, here, we initialize stack frame with
2909   //          "store-reg" instructions.
2910   // Case #2. Var-args function, that doesn't contain byval parameters.
2911   //          The same: eat all remained unallocated registers,
2912   //          initialize stack frame.
2913
2914   MachineFunction &MF = DAG.getMachineFunction();
2915   MachineFrameInfo *MFI = MF.getFrameInfo();
2916   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2917   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2918   unsigned RBegin, REnd;
2919   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2920     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2921     firstRegToSaveIndex = RBegin - ARM::R0;
2922     lastRegToSaveIndex = REnd - ARM::R0;
2923   } else {
2924     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2925       (GPRArgRegs, array_lengthof(GPRArgRegs));
2926     lastRegToSaveIndex = 4;
2927   }
2928
2929   unsigned ArgRegsSize, ArgRegsSaveSize;
2930   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2931                  ArgRegsSize, ArgRegsSaveSize);
2932
2933   // Store any by-val regs to their spots on the stack so that they may be
2934   // loaded by deferencing the result of formal parameter pointer or va_next.
2935   // Note: once stack area for byval/varargs registers
2936   // was initialized, it can't be initialized again.
2937   if (ArgRegsSaveSize) {
2938     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2939
2940     if (Padding) {
2941       assert(AFI->getStoredByValParamsPadding() == 0 &&
2942              "The only parameter may be padded.");
2943       AFI->setStoredByValParamsPadding(Padding);
2944     }
2945
2946     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2947                                             Padding +
2948                                               ByValStoreOffset -
2949                                               (int64_t)TotalArgRegsSaveSize,
2950                                             false);
2951     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2952     if (Padding) {
2953        MFI->CreateFixedObject(Padding,
2954                               ArgOffset + ByValStoreOffset -
2955                                 (int64_t)ArgRegsSaveSize,
2956                               false);
2957     }
2958
2959     SmallVector<SDValue, 4> MemOps;
2960     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2961          ++firstRegToSaveIndex, ++i) {
2962       const TargetRegisterClass *RC;
2963       if (AFI->isThumb1OnlyFunction())
2964         RC = &ARM::tGPRRegClass;
2965       else
2966         RC = &ARM::GPRRegClass;
2967
2968       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2969       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2970       SDValue Store =
2971         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2972                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2973                      false, false, 0);
2974       MemOps.push_back(Store);
2975       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2976                         DAG.getConstant(4, getPointerTy()));
2977     }
2978
2979     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2980
2981     if (!MemOps.empty())
2982       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2983     return FrameIndex;
2984   } else {
2985     if (ArgSize == 0) {
2986       // We cannot allocate a zero-byte object for the first variadic argument,
2987       // so just make up a size.
2988       ArgSize = 4;
2989     }
2990     // This will point to the next argument passed via stack.
2991     return MFI->CreateFixedObject(
2992       ArgSize, ArgOffset, !ForceMutable);
2993   }
2994 }
2995
2996 // Setup stack frame, the va_list pointer will start from.
2997 void
2998 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2999                                         SDLoc dl, SDValue &Chain,
3000                                         unsigned ArgOffset,
3001                                         unsigned TotalArgRegsSaveSize,
3002                                         bool ForceMutable) const {
3003   MachineFunction &MF = DAG.getMachineFunction();
3004   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3005
3006   // Try to store any remaining integer argument regs
3007   // to their spots on the stack so that they may be loaded by deferencing
3008   // the result of va_next.
3009   // If there is no regs to be stored, just point address after last
3010   // argument passed via stack.
3011   int FrameIndex =
3012     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3013                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
3014                    0, TotalArgRegsSaveSize);
3015
3016   AFI->setVarArgsFrameIndex(FrameIndex);
3017 }
3018
3019 SDValue
3020 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3021                                         CallingConv::ID CallConv, bool isVarArg,
3022                                         const SmallVectorImpl<ISD::InputArg>
3023                                           &Ins,
3024                                         SDLoc dl, SelectionDAG &DAG,
3025                                         SmallVectorImpl<SDValue> &InVals)
3026                                           const {
3027   MachineFunction &MF = DAG.getMachineFunction();
3028   MachineFrameInfo *MFI = MF.getFrameInfo();
3029
3030   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3031
3032   // Assign locations to all of the incoming arguments.
3033   SmallVector<CCValAssign, 16> ArgLocs;
3034   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3035                     *DAG.getContext(), Prologue);
3036   CCInfo.AnalyzeFormalArguments(Ins,
3037                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3038                                                   isVarArg));
3039
3040   SmallVector<SDValue, 16> ArgValues;
3041   int lastInsIndex = -1;
3042   SDValue ArgValue;
3043   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3044   unsigned CurArgIdx = 0;
3045
3046   // Initially ArgRegsSaveSize is zero.
3047   // Then we increase this value each time we meet byval parameter.
3048   // We also increase this value in case of varargs function.
3049   AFI->setArgRegsSaveSize(0);
3050
3051   unsigned ByValStoreOffset = 0;
3052   unsigned TotalArgRegsSaveSize = 0;
3053   unsigned ArgRegsSaveSizeMaxAlign = 4;
3054
3055   // Calculate the amount of stack space that we need to allocate to store
3056   // byval and variadic arguments that are passed in registers.
3057   // We need to know this before we allocate the first byval or variadic
3058   // argument, as they will be allocated a stack slot below the CFA (Canonical
3059   // Frame Address, the stack pointer at entry to the function).
3060   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3061     CCValAssign &VA = ArgLocs[i];
3062     if (VA.isMemLoc()) {
3063       int index = VA.getValNo();
3064       if (index != lastInsIndex) {
3065         ISD::ArgFlagsTy Flags = Ins[index].Flags;
3066         if (Flags.isByVal()) {
3067           unsigned ExtraArgRegsSize;
3068           unsigned ExtraArgRegsSaveSize;
3069           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProcessed(),
3070                          Flags.getByValSize(),
3071                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
3072
3073           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3074           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3075               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3076           CCInfo.nextInRegsParam();
3077         }
3078         lastInsIndex = index;
3079       }
3080     }
3081   }
3082   CCInfo.rewindByValRegsInfo();
3083   lastInsIndex = -1;
3084   if (isVarArg && MFI->hasVAStart()) {
3085     unsigned ExtraArgRegsSize;
3086     unsigned ExtraArgRegsSaveSize;
3087     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3088                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
3089     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3090   }
3091   // If the arg regs save area contains N-byte aligned values, the
3092   // bottom of it must be at least N-byte aligned.
3093   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3094   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3095
3096   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3097     CCValAssign &VA = ArgLocs[i];
3098     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3099     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3100     // Arguments stored in registers.
3101     if (VA.isRegLoc()) {
3102       EVT RegVT = VA.getLocVT();
3103
3104       if (VA.needsCustom()) {
3105         // f64 and vector types are split up into multiple registers or
3106         // combinations of registers and stack slots.
3107         if (VA.getLocVT() == MVT::v2f64) {
3108           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3109                                                    Chain, DAG, dl);
3110           VA = ArgLocs[++i]; // skip ahead to next loc
3111           SDValue ArgValue2;
3112           if (VA.isMemLoc()) {
3113             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3114             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3115             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3116                                     MachinePointerInfo::getFixedStack(FI),
3117                                     false, false, false, 0);
3118           } else {
3119             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3120                                              Chain, DAG, dl);
3121           }
3122           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3123           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3124                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3125           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3126                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3127         } else
3128           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3129
3130       } else {
3131         const TargetRegisterClass *RC;
3132
3133         if (RegVT == MVT::f32)
3134           RC = &ARM::SPRRegClass;
3135         else if (RegVT == MVT::f64)
3136           RC = &ARM::DPRRegClass;
3137         else if (RegVT == MVT::v2f64)
3138           RC = &ARM::QPRRegClass;
3139         else if (RegVT == MVT::i32)
3140           RC = AFI->isThumb1OnlyFunction() ?
3141             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3142             (const TargetRegisterClass*)&ARM::GPRRegClass;
3143         else
3144           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3145
3146         // Transform the arguments in physical registers into virtual ones.
3147         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3148         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3149       }
3150
3151       // If this is an 8 or 16-bit value, it is really passed promoted
3152       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3153       // truncate to the right size.
3154       switch (VA.getLocInfo()) {
3155       default: llvm_unreachable("Unknown loc info!");
3156       case CCValAssign::Full: break;
3157       case CCValAssign::BCvt:
3158         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3159         break;
3160       case CCValAssign::SExt:
3161         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3162                                DAG.getValueType(VA.getValVT()));
3163         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3164         break;
3165       case CCValAssign::ZExt:
3166         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3167                                DAG.getValueType(VA.getValVT()));
3168         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3169         break;
3170       }
3171
3172       InVals.push_back(ArgValue);
3173
3174     } else { // VA.isRegLoc()
3175
3176       // sanity check
3177       assert(VA.isMemLoc());
3178       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3179
3180       int index = ArgLocs[i].getValNo();
3181
3182       // Some Ins[] entries become multiple ArgLoc[] entries.
3183       // Process them only once.
3184       if (index != lastInsIndex)
3185         {
3186           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3187           // FIXME: For now, all byval parameter objects are marked mutable.
3188           // This can be changed with more analysis.
3189           // In case of tail call optimization mark all arguments mutable.
3190           // Since they could be overwritten by lowering of arguments in case of
3191           // a tail call.
3192           if (Flags.isByVal()) {
3193             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3194
3195             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3196             int FrameIndex = StoreByValRegs(
3197                 CCInfo, DAG, dl, Chain, CurOrigArg,
3198                 CurByValIndex,
3199                 Ins[VA.getValNo()].PartOffset,
3200                 VA.getLocMemOffset(),
3201                 Flags.getByValSize(),
3202                 true /*force mutable frames*/,
3203                 ByValStoreOffset,
3204                 TotalArgRegsSaveSize);
3205             ByValStoreOffset += Flags.getByValSize();
3206             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3207             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3208             CCInfo.nextInRegsParam();
3209           } else {
3210             unsigned FIOffset = VA.getLocMemOffset();
3211             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3212                                             FIOffset, true);
3213
3214             // Create load nodes to retrieve arguments from the stack.
3215             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3216             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3217                                          MachinePointerInfo::getFixedStack(FI),
3218                                          false, false, false, 0));
3219           }
3220           lastInsIndex = index;
3221         }
3222     }
3223   }
3224
3225   // varargs
3226   if (isVarArg && MFI->hasVAStart())
3227     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3228                          CCInfo.getNextStackOffset(),
3229                          TotalArgRegsSaveSize);
3230
3231   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3232
3233   return Chain;
3234 }
3235
3236 /// isFloatingPointZero - Return true if this is +0.0.
3237 static bool isFloatingPointZero(SDValue Op) {
3238   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3239     return CFP->getValueAPF().isPosZero();
3240   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3241     // Maybe this has already been legalized into the constant pool?
3242     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3243       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3244       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3245         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3246           return CFP->getValueAPF().isPosZero();
3247     }
3248   } else if (Op->getOpcode() == ISD::BITCAST &&
3249              Op->getValueType(0) == MVT::f64) {
3250     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3251     // created by LowerConstantFP().
3252     SDValue BitcastOp = Op->getOperand(0);
3253     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3254       SDValue MoveOp = BitcastOp->getOperand(0);
3255       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3256           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3257         return true;
3258       }
3259     }
3260   }
3261   return false;
3262 }
3263
3264 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3265 /// the given operands.
3266 SDValue
3267 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3268                              SDValue &ARMcc, SelectionDAG &DAG,
3269                              SDLoc dl) const {
3270   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3271     unsigned C = RHSC->getZExtValue();
3272     if (!isLegalICmpImmediate(C)) {
3273       // Constant does not fit, try adjusting it by one?
3274       switch (CC) {
3275       default: break;
3276       case ISD::SETLT:
3277       case ISD::SETGE:
3278         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3279           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3280           RHS = DAG.getConstant(C-1, MVT::i32);
3281         }
3282         break;
3283       case ISD::SETULT:
3284       case ISD::SETUGE:
3285         if (C != 0 && isLegalICmpImmediate(C-1)) {
3286           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3287           RHS = DAG.getConstant(C-1, MVT::i32);
3288         }
3289         break;
3290       case ISD::SETLE:
3291       case ISD::SETGT:
3292         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3293           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;