LLVM  9.0.0svn
ARMISelLowering.cpp
Go to the documentation of this file.
1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that ARM uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "ARMISelLowering.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMPerfectShuffle.h"
21 #include "ARMRegisterInfo.h"
22 #include "ARMSelectionDAGInfo.h"
23 #include "ARMSubtarget.h"
26 #include "Utils/ARMBaseInfo.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/APInt.h"
29 #include "llvm/ADT/ArrayRef.h"
30 #include "llvm/ADT/BitVector.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ADT/StringSwitch.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/ADT/Twine.h"
64 #include "llvm/IR/Attributes.h"
65 #include "llvm/IR/CallingConv.h"
66 #include "llvm/IR/Constant.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DebugLoc.h"
70 #include "llvm/IR/DerivedTypes.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/IR/GlobalAlias.h"
73 #include "llvm/IR/GlobalValue.h"
74 #include "llvm/IR/GlobalVariable.h"
75 #include "llvm/IR/IRBuilder.h"
76 #include "llvm/IR/InlineAsm.h"
77 #include "llvm/IR/Instruction.h"
78 #include "llvm/IR/Instructions.h"
79 #include "llvm/IR/IntrinsicInst.h"
80 #include "llvm/IR/Intrinsics.h"
81 #include "llvm/IR/Module.h"
82 #include "llvm/IR/PatternMatch.h"
83 #include "llvm/IR/Type.h"
84 #include "llvm/IR/User.h"
85 #include "llvm/IR/Value.h"
86 #include "llvm/MC/MCInstrDesc.h"
88 #include "llvm/MC/MCRegisterInfo.h"
89 #include "llvm/MC/MCSchedule.h"
92 #include "llvm/Support/Casting.h"
93 #include "llvm/Support/CodeGen.h"
95 #include "llvm/Support/Compiler.h"
96 #include "llvm/Support/Debug.h"
98 #include "llvm/Support/KnownBits.h"
100 #include "llvm/Support/MathExtras.h"
104 #include <algorithm>
105 #include <cassert>
106 #include <cstdint>
107 #include <cstdlib>
108 #include <iterator>
109 #include <limits>
110 #include <string>
111 #include <tuple>
112 #include <utility>
113 #include <vector>
114 
115 using namespace llvm;
116 using namespace llvm::PatternMatch;
117 
118 #define DEBUG_TYPE "arm-isel"
119 
120 STATISTIC(NumTailCalls, "Number of tail calls");
121 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
122 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
123 STATISTIC(NumConstpoolPromoted,
124  "Number of constants with their storage promoted into constant pools");
125 
126 static cl::opt<bool>
127 ARMInterworking("arm-interworking", cl::Hidden,
128  cl::desc("Enable / disable ARM interworking (for debugging only)"),
129  cl::init(true));
130 
132  "arm-promote-constant", cl::Hidden,
133  cl::desc("Enable / disable promotion of unnamed_addr constants into "
134  "constant pools"),
135  cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
137  "arm-promote-constant-max-size", cl::Hidden,
138  cl::desc("Maximum size of constant to promote into a constant pool"),
139  cl::init(64));
141  "arm-promote-constant-max-total", cl::Hidden,
142  cl::desc("Maximum size of ALL constants to promote into a constant pool"),
143  cl::init(128));
144 
145 // The APCS parameter registers.
146 static const MCPhysReg GPRArgRegs[] = {
147  ARM::R0, ARM::R1, ARM::R2, ARM::R3
148 };
149 
150 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
151  MVT PromotedBitwiseVT) {
152  if (VT != PromotedLdStVT) {
153  setOperationAction(ISD::LOAD, VT, Promote);
154  AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
155 
156  setOperationAction(ISD::STORE, VT, Promote);
157  AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
158  }
159 
160  MVT ElemTy = VT.getVectorElementType();
161  if (ElemTy != MVT::f64)
162  setOperationAction(ISD::SETCC, VT, Custom);
163  setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
164  setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
165  if (ElemTy == MVT::i32) {
166  setOperationAction(ISD::SINT_TO_FP, VT, Custom);
167  setOperationAction(ISD::UINT_TO_FP, VT, Custom);
168  setOperationAction(ISD::FP_TO_SINT, VT, Custom);
169  setOperationAction(ISD::FP_TO_UINT, VT, Custom);
170  } else {
171  setOperationAction(ISD::SINT_TO_FP, VT, Expand);
172  setOperationAction(ISD::UINT_TO_FP, VT, Expand);
173  setOperationAction(ISD::FP_TO_SINT, VT, Expand);
174  setOperationAction(ISD::FP_TO_UINT, VT, Expand);
175  }
176  setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
177  setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
178  setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
179  setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
180  setOperationAction(ISD::SELECT, VT, Expand);
181  setOperationAction(ISD::SELECT_CC, VT, Expand);
182  setOperationAction(ISD::VSELECT, VT, Expand);
183  setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
184  if (VT.isInteger()) {
185  setOperationAction(ISD::SHL, VT, Custom);
186  setOperationAction(ISD::SRA, VT, Custom);
187  setOperationAction(ISD::SRL, VT, Custom);
188  }
189 
190  // Promote all bit-wise operations.
191  if (VT.isInteger() && VT != PromotedBitwiseVT) {
192  setOperationAction(ISD::AND, VT, Promote);
193  AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
194  setOperationAction(ISD::OR, VT, Promote);
195  AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
196  setOperationAction(ISD::XOR, VT, Promote);
197  AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
198  }
199 
200  // Neon does not support vector divide/remainder operations.
201  setOperationAction(ISD::SDIV, VT, Expand);
202  setOperationAction(ISD::UDIV, VT, Expand);
203  setOperationAction(ISD::FDIV, VT, Expand);
204  setOperationAction(ISD::SREM, VT, Expand);
205  setOperationAction(ISD::UREM, VT, Expand);
206  setOperationAction(ISD::FREM, VT, Expand);
207 
208  if (!VT.isFloatingPoint() &&
209  VT != MVT::v2i64 && VT != MVT::v1i64)
210  for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
211  setOperationAction(Opcode, VT, Legal);
212 }
213 
214 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
215  addRegisterClass(VT, &ARM::DPRRegClass);
216  addTypeForNEON(VT, MVT::f64, MVT::v2i32);
217 }
218 
219 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
220  addRegisterClass(VT, &ARM::DPairRegClass);
221  addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
222 }
223 
225  const ARMSubtarget &STI)
226  : TargetLowering(TM), Subtarget(&STI) {
227  RegInfo = Subtarget->getRegisterInfo();
228  Itins = Subtarget->getInstrItineraryData();
229 
232 
233  if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
234  !Subtarget->isTargetWatchOS()) {
235  bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
236  for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
237  setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
238  IsHFTarget ? CallingConv::ARM_AAPCS_VFP
240  }
241 
242  if (Subtarget->isTargetMachO()) {
243  // Uses VFP for Thumb libfuncs if available.
244  if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
245  Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
246  static const struct {
247  const RTLIB::Libcall Op;
248  const char * const Name;
249  const ISD::CondCode Cond;
250  } LibraryCalls[] = {
251  // Single-precision floating-point arithmetic.
252  { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
253  { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
254  { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
255  { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
256 
257  // Double-precision floating-point arithmetic.
258  { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
259  { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
260  { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
261  { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
262 
263  // Single-precision comparisons.
264  { RTLIB::OEQ_F32, "__eqsf2vfp", ISD::SETNE },
265  { RTLIB::UNE_F32, "__nesf2vfp", ISD::SETNE },
266  { RTLIB::OLT_F32, "__ltsf2vfp", ISD::SETNE },
267  { RTLIB::OLE_F32, "__lesf2vfp", ISD::SETNE },
268  { RTLIB::OGE_F32, "__gesf2vfp", ISD::SETNE },
269  { RTLIB::OGT_F32, "__gtsf2vfp", ISD::SETNE },
270  { RTLIB::UO_F32, "__unordsf2vfp", ISD::SETNE },
271  { RTLIB::O_F32, "__unordsf2vfp", ISD::SETEQ },
272 
273  // Double-precision comparisons.
274  { RTLIB::OEQ_F64, "__eqdf2vfp", ISD::SETNE },
275  { RTLIB::UNE_F64, "__nedf2vfp", ISD::SETNE },
276  { RTLIB::OLT_F64, "__ltdf2vfp", ISD::SETNE },
277  { RTLIB::OLE_F64, "__ledf2vfp", ISD::SETNE },
278  { RTLIB::OGE_F64, "__gedf2vfp", ISD::SETNE },
279  { RTLIB::OGT_F64, "__gtdf2vfp", ISD::SETNE },
280  { RTLIB::UO_F64, "__unorddf2vfp", ISD::SETNE },
281  { RTLIB::O_F64, "__unorddf2vfp", ISD::SETEQ },
282 
283  // Floating-point to integer conversions.
284  // i64 conversions are done via library routines even when generating VFP
285  // instructions, so use the same ones.
286  { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp", ISD::SETCC_INVALID },
287  { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
288  { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp", ISD::SETCC_INVALID },
289  { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
290 
291  // Conversions between floating types.
292  { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp", ISD::SETCC_INVALID },
293  { RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp", ISD::SETCC_INVALID },
294 
295  // Integer to floating-point conversions.
296  // i64 conversions are done via library routines even when generating VFP
297  // instructions, so use the same ones.
298  // FIXME: There appears to be some naming inconsistency in ARM libgcc:
299  // e.g., __floatunsidf vs. __floatunssidfvfp.
300  { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp", ISD::SETCC_INVALID },
301  { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
302  { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp", ISD::SETCC_INVALID },
303  { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
304  };
305 
306  for (const auto &LC : LibraryCalls) {
307  setLibcallName(LC.Op, LC.Name);
308  if (LC.Cond != ISD::SETCC_INVALID)
309  setCmpLibcallCC(LC.Op, LC.Cond);
310  }
311  }
312  }
313 
314  // These libcalls are not available in 32-bit.
315  setLibcallName(RTLIB::SHL_I128, nullptr);
316  setLibcallName(RTLIB::SRL_I128, nullptr);
317  setLibcallName(RTLIB::SRA_I128, nullptr);
318 
319  // RTLIB
320  if (Subtarget->isAAPCS_ABI() &&
321  (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
322  Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
323  static const struct {
324  const RTLIB::Libcall Op;
325  const char * const Name;
326  const CallingConv::ID CC;
327  const ISD::CondCode Cond;
328  } LibraryCalls[] = {
329  // Double-precision floating-point arithmetic helper functions
330  // RTABI chapter 4.1.2, Table 2
331  { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332  { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333  { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334  { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 
336  // Double-precision floating-point comparison helper functions
337  // RTABI chapter 4.1.2, Table 3
338  { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
339  { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
340  { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
341  { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
342  { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
343  { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
344  { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
345  { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
346 
347  // Single-precision floating-point arithmetic helper functions
348  // RTABI chapter 4.1.2, Table 4
349  { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350  { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351  { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352  { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
353 
354  // Single-precision floating-point comparison helper functions
355  // RTABI chapter 4.1.2, Table 5
356  { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
357  { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
358  { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
359  { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
360  { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
361  { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
362  { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
363  { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
364 
365  // Floating-point to integer conversions.
366  // RTABI chapter 4.1.2, Table 6
367  { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
368  { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
369  { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
370  { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
371  { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
372  { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
373  { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
374  { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
375 
376  // Conversions between floating types.
377  // RTABI chapter 4.1.2, Table 7
378  { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
379  { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
380  { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
381 
382  // Integer to floating-point conversions.
383  // RTABI chapter 4.1.2, Table 8
384  { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
385  { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
386  { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
387  { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
388  { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
389  { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
390  { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
391  { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
392 
393  // Long long helper functions
394  // RTABI chapter 4.2, Table 9
395  { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
396  { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
397  { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
398  { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
399 
400  // Integer division functions
401  // RTABI chapter 4.3.1
402  { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
403  { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
404  { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
405  { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
406  { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
407  { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
408  { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
409  { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
410  };
411 
412  for (const auto &LC : LibraryCalls) {
413  setLibcallName(LC.Op, LC.Name);
414  setLibcallCallingConv(LC.Op, LC.CC);
415  if (LC.Cond != ISD::SETCC_INVALID)
416  setCmpLibcallCC(LC.Op, LC.Cond);
417  }
418 
419  // EABI dependent RTLIB
420  if (TM.Options.EABIVersion == EABI::EABI4 ||
422  static const struct {
423  const RTLIB::Libcall Op;
424  const char *const Name;
425  const CallingConv::ID CC;
426  const ISD::CondCode Cond;
427  } MemOpsLibraryCalls[] = {
428  // Memory operations
429  // RTABI chapter 4.3.4
431  { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
432  { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
433  };
434 
435  for (const auto &LC : MemOpsLibraryCalls) {
436  setLibcallName(LC.Op, LC.Name);
437  setLibcallCallingConv(LC.Op, LC.CC);
438  if (LC.Cond != ISD::SETCC_INVALID)
439  setCmpLibcallCC(LC.Op, LC.Cond);
440  }
441  }
442  }
443 
444  if (Subtarget->isTargetWindows()) {
445  static const struct {
446  const RTLIB::Libcall Op;
447  const char * const Name;
448  const CallingConv::ID CC;
449  } LibraryCalls[] = {
450  { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
451  { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
452  { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
453  { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
454  { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
455  { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
456  { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
457  { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
458  };
459 
460  for (const auto &LC : LibraryCalls) {
461  setLibcallName(LC.Op, LC.Name);
462  setLibcallCallingConv(LC.Op, LC.CC);
463  }
464  }
465 
466  // Use divmod compiler-rt calls for iOS 5.0 and later.
467  if (Subtarget->isTargetMachO() &&
468  !(Subtarget->isTargetIOS() &&
469  Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
470  setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
471  setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
472  }
473 
474  // The half <-> float conversion functions are always soft-float on
475  // non-watchos platforms, but are needed for some targets which use a
476  // hard-float calling convention by default.
477  if (!Subtarget->isTargetWatchABI()) {
478  if (Subtarget->isAAPCS_ABI()) {
479  setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
480  setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
481  setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
482  } else {
483  setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
484  setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
485  setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
486  }
487  }
488 
489  // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
490  // a __gnu_ prefix (which is the default).
491  if (Subtarget->isTargetAEABI()) {
492  static const struct {
493  const RTLIB::Libcall Op;
494  const char * const Name;
495  const CallingConv::ID CC;
496  } LibraryCalls[] = {
497  { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
498  { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
499  { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
500  };
501 
502  for (const auto &LC : LibraryCalls) {
503  setLibcallName(LC.Op, LC.Name);
504  setLibcallCallingConv(LC.Op, LC.CC);
505  }
506  }
507 
508  if (Subtarget->isThumb1Only())
509  addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
510  else
511  addRegisterClass(MVT::i32, &ARM::GPRRegClass);
512 
513  if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
514  !Subtarget->isThumb1Only()) {
515  addRegisterClass(MVT::f32, &ARM::SPRRegClass);
516  addRegisterClass(MVT::f64, &ARM::DPRRegClass);
517  }
518 
519  if (Subtarget->hasFullFP16()) {
520  addRegisterClass(MVT::f16, &ARM::HPRRegClass);
524 
527  }
528 
529  for (MVT VT : MVT::vector_valuetypes()) {
530  for (MVT InnerVT : MVT::vector_valuetypes()) {
531  setTruncStoreAction(VT, InnerVT, Expand);
532  setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
533  setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
534  setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
535  }
536 
541 
543  }
544 
547 
550 
551  if (Subtarget->hasNEON()) {
552  addDRTypeForNEON(MVT::v2f32);
553  addDRTypeForNEON(MVT::v8i8);
554  addDRTypeForNEON(MVT::v4i16);
555  addDRTypeForNEON(MVT::v2i32);
556  addDRTypeForNEON(MVT::v1i64);
557 
558  addQRTypeForNEON(MVT::v4f32);
559  addQRTypeForNEON(MVT::v2f64);
560  addQRTypeForNEON(MVT::v16i8);
561  addQRTypeForNEON(MVT::v8i16);
562  addQRTypeForNEON(MVT::v4i32);
563  addQRTypeForNEON(MVT::v2i64);
564 
565  if (Subtarget->hasFullFP16()) {
566  addQRTypeForNEON(MVT::v8f16);
567  addDRTypeForNEON(MVT::v4f16);
568  }
569 
570  // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
571  // neither Neon nor VFP support any arithmetic operations on it.
572  // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
573  // supported for v4f32.
577  // FIXME: Code duplication: FDIV and FREM are expanded always, see
578  // ARMTargetLowering::addTypeForNEON method for details.
581  // FIXME: Create unittest.
582  // In another words, find a way when "copysign" appears in DAG with vector
583  // operands.
585  // FIXME: Code duplication: SETCC has custom operation action, see
586  // ARMTargetLowering::addTypeForNEON method for details.
588  // FIXME: Create unittest for FNEG and for FABS.
600  // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
607 
622 
623  // Mark v2f32 intrinsics.
638 
639  // Neon does not support some operations on v1i64 and v2i64 types.
641  // Custom handling for some quad-vector types to detect VMULL.
645  // Custom handling for some vector types to avoid expensive expansions
650  // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
651  // a destination type that is wider than the source, and nor does
652  // it have a FP_TO_[SU]INT instruction with a narrower destination than
653  // source.
662 
665 
666  // NEON does not have single instruction CTPOP for vectors with element
667  // types wider than 8-bits. However, custom lowering can leverage the
668  // v8i8/v16i8 vcnt instruction.
675 
678 
679  // NEON does not have single instruction CTTZ for vectors.
684 
689 
694 
699 
700  // NEON only has FMA instructions as of VFP4.
701  if (!Subtarget->hasVFP4()) {
704  }
705 
723 
724  // It is legal to extload from v4i8 to v4i16 or v4i32.
726  MVT::v2i32}) {
727  for (MVT VT : MVT::integer_vector_valuetypes()) {
731  }
732  }
733  }
734 
735  if (Subtarget->isFPOnlySP()) {
736  // When targeting a floating-point unit with only single-precision
737  // operations, f64 is legal for the few double-precision instructions which
738  // are present However, no double-precision operations other than moves,
739  // loads and stores are provided by the hardware.
772  }
773 
775 
776  // ARM does not have floating-point extending loads.
777  for (MVT VT : MVT::fp_valuetypes()) {
780  }
781 
782  // ... or truncating stores
786 
787  // ARM does not have i1 sign extending load.
788  for (MVT VT : MVT::integer_valuetypes())
790 
791  // ARM supports all 4 flavors of integer indexed load / store.
792  if (!Subtarget->isThumb1Only()) {
793  for (unsigned im = (unsigned)ISD::PRE_INC;
803  }
804  } else {
805  // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
808  }
809 
814 
817 
818  // i64 operation support.
821  if (Subtarget->isThumb1Only()) {
824  }
825  if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
826  || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
828 
835 
836  // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
837  if (Subtarget->isThumb1Only()) {
841  }
842 
843  if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
845 
846  // ARM does not have ROTL.
848  for (MVT VT : MVT::vector_valuetypes()) {
851  }
854  if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
857  }
858 
859  // @llvm.readcyclecounter requires the Performance Monitors extension.
860  // Default to the 0 expansion on unsupported platforms.
861  // FIXME: Technically there are older ARM CPUs that have
862  // implementation-specific ways of obtaining this information.
863  if (Subtarget->hasPerfMon())
865 
866  // Only ARMv6 has BSWAP.
867  if (!Subtarget->hasV6Ops())
869 
870  bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
871  : Subtarget->hasDivideInARMMode();
872  if (!hasDivide) {
873  // These are expanded into libcalls if the cpu doesn't have HW divider.
876  }
877 
878  if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
881 
884  }
885 
888 
889  // Register based DivRem for AEABI (RTABI 4.2)
890  if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
891  Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
892  Subtarget->isTargetWindows()) {
895  HasStandaloneRem = false;
896 
897  if (Subtarget->isTargetWindows()) {
898  const struct {
899  const RTLIB::Libcall Op;
900  const char * const Name;
901  const CallingConv::ID CC;
902  } LibraryCalls[] = {
903  { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
904  { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
905  { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
906  { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
907 
908  { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
909  { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
910  { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
911  { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
912  };
913 
914  for (const auto &LC : LibraryCalls) {
915  setLibcallName(LC.Op, LC.Name);
916  setLibcallCallingConv(LC.Op, LC.CC);
917  }
918  } else {
919  const struct {
920  const RTLIB::Libcall Op;
921  const char * const Name;
922  const CallingConv::ID CC;
923  } LibraryCalls[] = {
924  { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
925  { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
926  { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
927  { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
928 
929  { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
930  { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
931  { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
932  { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
933  };
934 
935  for (const auto &LC : LibraryCalls) {
936  setLibcallName(LC.Op, LC.Name);
937  setLibcallCallingConv(LC.Op, LC.CC);
938  }
939  }
940 
945  } else {
948  }
949 
950  if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
951  for (auto &VT : {MVT::f32, MVT::f64})
953 
958 
961 
962  // Use the default implementation.
969 
970  if (Subtarget->isTargetWindows())
972  else
974 
975  // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
976  // the default expansion.
977  InsertFencesForAtomic = false;
978  if (Subtarget->hasAnyDataBarrier() &&
979  (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
980  // ATOMIC_FENCE needs custom lowering; the others should have been expanded
981  // to ldrex/strex loops already.
983  if (!Subtarget->isThumb() || !Subtarget->isMClass())
985 
986  // On v8, we have particularly efficient implementations of atomic fences
987  // if they can be combined with nearby atomic loads and stores.
988  if (!Subtarget->hasAcquireRelease() ||
989  getTargetMachine().getOptLevel() == 0) {
990  // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
991  InsertFencesForAtomic = true;
992  }
993  } else {
994  // If there's anything we can use as a barrier, go through custom lowering
995  // for ATOMIC_FENCE.
996  // If target has DMB in thumb, Fences can be inserted.
997  if (Subtarget->hasDataBarrier())
998  InsertFencesForAtomic = true;
999 
1001  Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1002 
1003  // Set them all for expansion, which will force libcalls.
1016  // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1017  // Unordered/Monotonic case.
1018  if (!InsertFencesForAtomic) {
1021  }
1022  }
1023 
1025 
1026  // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1027  if (!Subtarget->hasV6Ops()) {
1030  }
1032 
1033  if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1034  !Subtarget->isThumb1Only()) {
1035  // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1036  // iff target supports vfp2.
1039  }
1040 
1041  // We want to custom lower some of our intrinsics.
1046  if (Subtarget->useSjLjEH())
1047  setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1048 
1058  if (Subtarget->hasFullFP16()) {
1062  }
1063 
1065 
1068  if (Subtarget->hasFullFP16())
1073 
1074  // We don't support sin/cos/fmod/copysign/pow
1083  if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1084  !Subtarget->isThumb1Only()) {
1087  }
1090 
1091  if (!Subtarget->hasVFP4()) {
1094  }
1095 
1096  // Various VFP goodness
1097  if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1098  // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1099  if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
1102  }
1103 
1104  // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1105  if (!Subtarget->hasFP16()) {
1108  }
1109  }
1110 
1111  // Use __sincos_stret if available.
1112  if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1113  getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1116  }
1117 
1118  // FP-ARMv8 implements a lot of rounding-like FP operations.
1119  if (Subtarget->hasFPARMv8()) {
1132 
1133  if (!Subtarget->isFPOnlySP()) {
1142  }
1143  }
1144 
1145  if (Subtarget->hasNEON()) {
1146  // vmin and vmax aren't available in a scalar form, so we use
1147  // a NEON instruction with an undef lane instead.
1156 
1157  if (Subtarget->hasFullFP16()) {
1162 
1167  }
1168  }
1169 
1170  // We have target-specific dag combine patterns for the following nodes:
1171  // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
1178 
1179  if (Subtarget->hasV6Ops())
1181  if (Subtarget->isThumb1Only())
1183 
1185 
1186  if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1187  !Subtarget->hasVFP2() || Subtarget->hasMinSize())
1189  else
1191 
1192  //// temporary - rewrite interface to use type
1193  MaxStoresPerMemset = 8;
1195  MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1197  MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1199 
1200  // On ARM arguments smaller than 4 bytes are extended, so all arguments
1201  // are at least 4 bytes aligned.
1203 
1204  // Prefer likely predicted branches to selects on out-of-order cores.
1205  PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1206 
1208 
1209  setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1210 
1211  if (Subtarget->isThumb() || Subtarget->isThumb2())
1213 }
1214 
1216  return Subtarget->useSoftFloat();
1217 }
1218 
1219 // FIXME: It might make sense to define the representative register class as the
1220 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1221 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1222 // SPR's representative would be DPR_VFP2. This should work well if register
1223 // pressure tracking were modified such that a register use would increment the
1224 // pressure of the register class's representative and all of it's super
1225 // classes' representatives transitively. We have not implemented this because
1226 // of the difficulty prior to coalescing of modeling operand register classes
1227 // due to the common occurrence of cross class copies and subregister insertions
1228 // and extractions.
1229 std::pair<const TargetRegisterClass *, uint8_t>
1231  MVT VT) const {
1232  const TargetRegisterClass *RRC = nullptr;
1233  uint8_t Cost = 1;
1234  switch (VT.SimpleTy) {
1235  default:
1237  // Use DPR as representative register class for all floating point
1238  // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1239  // the cost is 1 for both f32 and f64.
1240  case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1241  case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1242  RRC = &ARM::DPRRegClass;
1243  // When NEON is used for SP, only half of the register file is available
1244  // because operations that define both SP and DP results will be constrained
1245  // to the VFP2 class (D0-D15). We currently model this constraint prior to
1246  // coalescing by double-counting the SP regs. See the FIXME above.
1247  if (Subtarget->useNEONForSinglePrecisionFP())
1248  Cost = 2;
1249  break;
1250  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1251  case MVT::v4f32: case MVT::v2f64:
1252  RRC = &ARM::DPRRegClass;
1253  Cost = 2;
1254  break;
1255  case MVT::v4i64:
1256  RRC = &ARM::DPRRegClass;
1257  Cost = 4;
1258  break;
1259  case MVT::v8i64:
1260  RRC = &ARM::DPRRegClass;
1261  Cost = 8;
1262  break;
1263  }
1264  return std::make_pair(RRC, Cost);
1265 }
1266 
1267 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1268  switch ((ARMISD::NodeType)Opcode) {
1269  case ARMISD::FIRST_NUMBER: break;
1270  case ARMISD::Wrapper: return "ARMISD::Wrapper";
1271  case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1272  case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1273  case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1274  case ARMISD::CALL: return "ARMISD::CALL";
1275  case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1276  case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1277  case ARMISD::BRCOND: return "ARMISD::BRCOND";
1278  case ARMISD::BR_JT: return "ARMISD::BR_JT";
1279  case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1280  case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1281  case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1282  case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1283  case ARMISD::CMP: return "ARMISD::CMP";
1284  case ARMISD::CMN: return "ARMISD::CMN";
1285  case ARMISD::CMPZ: return "ARMISD::CMPZ";
1286  case ARMISD::CMPFP: return "ARMISD::CMPFP";
1287  case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1288  case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1289  case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1290 
1291  case ARMISD::CMOV: return "ARMISD::CMOV";
1292  case ARMISD::SUBS: return "ARMISD::SUBS";
1293 
1294  case ARMISD::SSAT: return "ARMISD::SSAT";
1295  case ARMISD::USAT: return "ARMISD::USAT";
1296 
1297  case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1298  case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1299  case ARMISD::RRX: return "ARMISD::RRX";
1300 
1301  case ARMISD::ADDC: return "ARMISD::ADDC";
1302  case ARMISD::ADDE: return "ARMISD::ADDE";
1303  case ARMISD::SUBC: return "ARMISD::SUBC";
1304  case ARMISD::SUBE: return "ARMISD::SUBE";
1305 
1306  case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1307  case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1308  case ARMISD::VMOVhr: return "ARMISD::VMOVhr";
1309  case ARMISD::VMOVrh: return "ARMISD::VMOVrh";
1310  case ARMISD::VMOVSR: return "ARMISD::VMOVSR";
1311 
1312  case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1313  case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1314  case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1315 
1316  case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1317 
1318  case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1319 
1320  case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1321 
1322  case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1323 
1324  case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1325 
1326  case ARMISD::WIN__CHKSTK: return "ARMISD::WIN__CHKSTK";
1327  case ARMISD::WIN__DBZCHK: return "ARMISD::WIN__DBZCHK";
1328 
1329  case ARMISD::VCEQ: return "ARMISD::VCEQ";
1330  case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1331  case ARMISD::VCGE: return "ARMISD::VCGE";
1332  case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1333  case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1334  case ARMISD::VCGEU: return "ARMISD::VCGEU";
1335  case ARMISD::VCGT: return "ARMISD::VCGT";
1336  case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1337  case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1338  case ARMISD::VCGTU: return "ARMISD::VCGTU";
1339  case ARMISD::VTST: return "ARMISD::VTST";
1340 
1341  case ARMISD::VSHL: return "ARMISD::VSHL";
1342  case ARMISD::VSHRs: return "ARMISD::VSHRs";
1343  case ARMISD::VSHRu: return "ARMISD::VSHRu";
1344  case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1345  case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1346  case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1347  case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1348  case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1349  case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1350  case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1351  case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1352  case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1353  case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1354  case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1355  case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1356  case ARMISD::VSLI: return "ARMISD::VSLI";
1357  case ARMISD::VSRI: return "ARMISD::VSRI";
1358  case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1359  case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1360  case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1361  case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1362  case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1363  case ARMISD::VDUP: return "ARMISD::VDUP";
1364  case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1365  case ARMISD::VEXT: return "ARMISD::VEXT";
1366  case ARMISD::VREV64: return "ARMISD::VREV64";
1367  case ARMISD::VREV32: return "ARMISD::VREV32";
1368  case ARMISD::VREV16: return "ARMISD::VREV16";
1369  case ARMISD::VZIP: return "ARMISD::VZIP";
1370  case ARMISD::VUZP: return "ARMISD::VUZP";
1371  case ARMISD::VTRN: return "ARMISD::VTRN";
1372  case ARMISD::VTBL1: return "ARMISD::VTBL1";
1373  case ARMISD::VTBL2: return "ARMISD::VTBL2";
1374  case ARMISD::VMULLs: return "ARMISD::VMULLs";
1375  case ARMISD::VMULLu: return "ARMISD::VMULLu";
1376  case ARMISD::UMAAL: return "ARMISD::UMAAL";
1377  case ARMISD::UMLAL: return "ARMISD::UMLAL";
1378  case ARMISD::SMLAL: return "ARMISD::SMLAL";
1379  case ARMISD::SMLALBB: return "ARMISD::SMLALBB";
1380  case ARMISD::SMLALBT: return "ARMISD::SMLALBT";
1381  case ARMISD::SMLALTB: return "ARMISD::SMLALTB";
1382  case ARMISD::SMLALTT: return "ARMISD::SMLALTT";
1383  case ARMISD::SMULWB: return "ARMISD::SMULWB";
1384  case ARMISD::SMULWT: return "ARMISD::SMULWT";
1385  case ARMISD::SMLALD: return "ARMISD::SMLALD";
1386  case ARMISD::SMLALDX: return "ARMISD::SMLALDX";
1387  case ARMISD::SMLSLD: return "ARMISD::SMLSLD";
1388  case ARMISD::SMLSLDX: return "ARMISD::SMLSLDX";
1389  case ARMISD::SMMLAR: return "ARMISD::SMMLAR";
1390  case ARMISD::SMMLSR: return "ARMISD::SMMLSR";
1391  case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1392  case ARMISD::BFI: return "ARMISD::BFI";
1393  case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1394  case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1395  case ARMISD::VBSL: return "ARMISD::VBSL";
1396  case ARMISD::MEMCPY: return "ARMISD::MEMCPY";
1397  case ARMISD::VLD1DUP: return "ARMISD::VLD1DUP";
1398  case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1399  case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1400  case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1401  case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1402  case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1403  case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1404  case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1405  case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1406  case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1407  case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1408  case ARMISD::VLD1DUP_UPD: return "ARMISD::VLD1DUP_UPD";
1409  case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1410  case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1411  case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1412  case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1413  case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1414  case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1415  case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1416  case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1417  case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1418  case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1419  }
1420  return nullptr;
1421 }
1422 
1424  EVT VT) const {
1425  if (!VT.isVector())
1426  return getPointerTy(DL);
1428 }
1429 
1430 /// getRegClassFor - Return the register class that should be used for the
1431 /// specified value type.
1433  // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1434  // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1435  // load / store 4 to 8 consecutive D registers.
1436  if (Subtarget->hasNEON()) {
1437  if (VT == MVT::v4i64)
1438  return &ARM::QQPRRegClass;
1439  if (VT == MVT::v8i64)
1440  return &ARM::QQQQPRRegClass;
1441  }
1442  return TargetLowering::getRegClassFor(VT);
1443 }
1444 
1445 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1446 // source/dest is aligned and the copy size is large enough. We therefore want
1447 // to align such objects passed to memory intrinsics.
1449  unsigned &PrefAlign) const {
1450  if (!isa<MemIntrinsic>(CI))
1451  return false;
1452  MinSize = 8;
1453  // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1454  // cycle faster than 4-byte aligned LDM.
1455  PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1456  return true;
1457 }
1458 
1459 // Create a fast isel object.
1460 FastISel *
1462  const TargetLibraryInfo *libInfo) const {
1463  return ARM::createFastISel(funcInfo, libInfo);
1464 }
1465 
1467  unsigned NumVals = N->getNumValues();
1468  if (!NumVals)
1469  return Sched::RegPressure;
1470 
1471  for (unsigned i = 0; i != NumVals; ++i) {
1472  EVT VT = N->getValueType(i);
1473  if (VT == MVT::Glue || VT == MVT::Other)
1474  continue;
1475  if (VT.isFloatingPoint() || VT.isVector())
1476  return Sched::ILP;
1477  }
1478 
1479  if (!N->isMachineOpcode())
1480  return Sched::RegPressure;
1481 
1482  // Load are scheduled for latency even if there instruction itinerary
1483  // is not available.
1484  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1485  const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1486 
1487  if (MCID.getNumDefs() == 0)
1488  return Sched::RegPressure;
1489  if (!Itins->isEmpty() &&
1490  Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1491  return Sched::ILP;
1492 
1493  return Sched::RegPressure;
1494 }
1495 
1496 //===----------------------------------------------------------------------===//
1497 // Lowering Code
1498 //===----------------------------------------------------------------------===//
1499 
1500 static bool isSRL16(const SDValue &Op) {
1501  if (Op.getOpcode() != ISD::SRL)
1502  return false;
1503  if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1504  return Const->getZExtValue() == 16;
1505  return false;
1506 }
1507 
1508 static bool isSRA16(const SDValue &Op) {
1509  if (Op.getOpcode() != ISD::SRA)
1510  return false;
1511  if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1512  return Const->getZExtValue() == 16;
1513  return false;
1514 }
1515 
1516 static bool isSHL16(const SDValue &Op) {
1517  if (Op.getOpcode() != ISD::SHL)
1518  return false;
1519  if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1520  return Const->getZExtValue() == 16;
1521  return false;
1522 }
1523 
1524 // Check for a signed 16-bit value. We special case SRA because it makes it
1525 // more simple when also looking for SRAs that aren't sign extending a
1526 // smaller value. Without the check, we'd need to take extra care with
1527 // checking order for some operations.
1528 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1529  if (isSRA16(Op))
1530  return isSHL16(Op.getOperand(0));
1531  return DAG.ComputeNumSignBits(Op) == 17;
1532 }
1533 
1534 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1536  switch (CC) {
1537  default: llvm_unreachable("Unknown condition code!");
1538  case ISD::SETNE: return ARMCC::NE;
1539  case ISD::SETEQ: return ARMCC::EQ;
1540  case ISD::SETGT: return ARMCC::GT;
1541  case ISD::SETGE: return ARMCC::GE;
1542  case ISD::SETLT: return ARMCC::LT;
1543  case ISD::SETLE: return ARMCC::LE;
1544  case ISD::SETUGT: return ARMCC::HI;
1545  case ISD::SETUGE: return ARMCC::HS;
1546  case ISD::SETULT: return ARMCC::LO;
1547  case ISD::SETULE: return ARMCC::LS;
1548  }
1549 }
1550 
1551 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1553  ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1554  CondCode2 = ARMCC::AL;
1555  InvalidOnQNaN = true;
1556  switch (CC) {
1557  default: llvm_unreachable("Unknown FP condition!");
1558  case ISD::SETEQ:
1559  case ISD::SETOEQ:
1560  CondCode = ARMCC::EQ;
1561  InvalidOnQNaN = false;
1562  break;
1563  case ISD::SETGT:
1564  case ISD::SETOGT: CondCode = ARMCC::GT; break;
1565  case ISD::SETGE:
1566  case ISD::SETOGE: CondCode = ARMCC::GE; break;
1567  case ISD::SETOLT: CondCode = ARMCC::MI; break;
1568  case ISD::SETOLE: CondCode = ARMCC::LS; break;
1569  case ISD::SETONE:
1570  CondCode = ARMCC::MI;
1571  CondCode2 = ARMCC::GT;
1572  InvalidOnQNaN = false;
1573  break;
1574  case ISD::SETO: CondCode = ARMCC::VC; break;
1575  case ISD::SETUO: CondCode = ARMCC::VS; break;
1576  case ISD::SETUEQ:
1577  CondCode = ARMCC::EQ;
1578  CondCode2 = ARMCC::VS;
1579  InvalidOnQNaN = false;
1580  break;
1581  case ISD::SETUGT: CondCode = ARMCC::HI; break;
1582  case ISD::SETUGE: CondCode = ARMCC::PL; break;
1583  case ISD::SETLT:
1584  case ISD::SETULT: CondCode = ARMCC::LT; break;
1585  case ISD::SETLE:
1586  case ISD::SETULE: CondCode = ARMCC::LE; break;
1587  case ISD::SETNE:
1588  case ISD::SETUNE:
1589  CondCode = ARMCC::NE;
1590  InvalidOnQNaN = false;
1591  break;
1592  }
1593 }
1594 
1595 //===----------------------------------------------------------------------===//
1596 // Calling Convention Implementation
1597 //===----------------------------------------------------------------------===//
1598 
1599 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1600 /// account presence of floating point hardware and calling convention
1601 /// limitations, such as support for variadic functions.
1603 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1604  bool isVarArg) const {
1605  switch (CC) {
1606  default:
1607  report_fatal_error("Unsupported calling convention");
1609  case CallingConv::ARM_APCS:
1610  case CallingConv::GHC:
1611  return CC;
1615  case CallingConv::Swift:
1617  case CallingConv::C:
1618  if (!Subtarget->isAAPCS_ABI())
1619  return CallingConv::ARM_APCS;
1620  else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1622  !isVarArg)
1624  else
1625  return CallingConv::ARM_AAPCS;
1626  case CallingConv::Fast:
1628  if (!Subtarget->isAAPCS_ABI()) {
1629  if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1630  return CallingConv::Fast;
1631  return CallingConv::ARM_APCS;
1632  } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1634  else
1635  return CallingConv::ARM_AAPCS;
1636  }
1637 }
1638 
1640  bool isVarArg) const {
1641  return CCAssignFnForNode(CC, false, isVarArg);
1642 }
1643 
1645  bool isVarArg) const {
1646  return CCAssignFnForNode(CC, true, isVarArg);
1647 }
1648 
1649 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1650 /// CallingConvention.
1651 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1652  bool Return,
1653  bool isVarArg) const {
1654  switch (getEffectiveCallingConv(CC, isVarArg)) {
1655  default:
1656  report_fatal_error("Unsupported calling convention");
1657  case CallingConv::ARM_APCS:
1658  return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1660  return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1662  return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1663  case CallingConv::Fast:
1664  return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1665  case CallingConv::GHC:
1666  return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1668  return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1669  }
1670 }
1671 
1672 /// LowerCallResult - Lower the result values of a call into the
1673 /// appropriate copies out of appropriate physical registers.
1674 SDValue ARMTargetLowering::LowerCallResult(
1675  SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1676  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1677  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1678  SDValue ThisVal) const {
1679  // Assign locations to each value returned by this call.
1681  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1682  *DAG.getContext());
1683  CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1684 
1685  // Copy all of the result registers out of their specified physreg.
1686  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1687  CCValAssign VA = RVLocs[i];
1688 
1689  // Pass 'this' value directly from the argument to return value, to avoid
1690  // reg unit interference
1691  if (i == 0 && isThisReturn) {
1692  assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1693  "unexpected return calling convention register assignment");
1694  InVals.push_back(ThisVal);
1695  continue;
1696  }
1697 
1698  SDValue Val;
1699  if (VA.needsCustom()) {
1700  // Handle f64 or half of a v2f64.
1701  SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1702  InFlag);
1703  Chain = Lo.getValue(1);
1704  InFlag = Lo.getValue(2);
1705  VA = RVLocs[++i]; // skip ahead to next loc
1706  SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1707  InFlag);
1708  Chain = Hi.getValue(1);
1709  InFlag = Hi.getValue(2);
1710  if (!Subtarget->isLittle())
1711  std::swap (Lo, Hi);
1712  Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1713 
1714  if (VA.getLocVT() == MVT::v2f64) {
1715  SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1716  Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1717  DAG.getConstant(0, dl, MVT::i32));
1718 
1719  VA = RVLocs[++i]; // skip ahead to next loc
1720  Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1721  Chain = Lo.getValue(1);
1722  InFlag = Lo.getValue(2);
1723  VA = RVLocs[++i]; // skip ahead to next loc
1724  Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1725  Chain = Hi.getValue(1);
1726  InFlag = Hi.getValue(2);
1727  if (!Subtarget->isLittle())
1728  std::swap (Lo, Hi);
1729  Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1730  Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1731  DAG.getConstant(1, dl, MVT::i32));
1732  }
1733  } else {
1734  Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1735  InFlag);
1736  Chain = Val.getValue(1);
1737  InFlag = Val.getValue(2);
1738  }
1739 
1740  switch (VA.getLocInfo()) {
1741  default: llvm_unreachable("Unknown loc info!");
1742  case CCValAssign::Full: break;
1743  case CCValAssign::BCvt:
1744  Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1745  break;
1746  }
1747 
1748  InVals.push_back(Val);
1749  }
1750 
1751  return Chain;
1752 }
1753 
1754 /// LowerMemOpCallTo - Store the argument to the stack.
1755 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1756  SDValue Arg, const SDLoc &dl,
1757  SelectionDAG &DAG,
1758  const CCValAssign &VA,
1759  ISD::ArgFlagsTy Flags) const {
1760  unsigned LocMemOffset = VA.getLocMemOffset();
1761  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1762  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1763  StackPtr, PtrOff);
1764  return DAG.getStore(
1765  Chain, dl, Arg, PtrOff,
1766  MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1767 }
1768 
1769 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1770  SDValue Chain, SDValue &Arg,
1771  RegsToPassVector &RegsToPass,
1772  CCValAssign &VA, CCValAssign &NextVA,
1773  SDValue &StackPtr,
1774  SmallVectorImpl<SDValue> &MemOpChains,
1775  ISD::ArgFlagsTy Flags) const {
1776  SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1777  DAG.getVTList(MVT::i32, MVT::i32), Arg);
1778  unsigned id = Subtarget->isLittle() ? 0 : 1;
1779  RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1780 
1781  if (NextVA.isRegLoc())
1782  RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1783  else {
1784  assert(NextVA.isMemLoc());
1785  if (!StackPtr.getNode())
1786  StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1787  getPointerTy(DAG.getDataLayout()));
1788 
1789  MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1790  dl, DAG, NextVA,
1791  Flags));
1792  }
1793 }
1794 
1795 /// LowerCall - Lowering a call into a callseq_start <-
1796 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1797 /// nodes.
1798 SDValue
1799 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1800  SmallVectorImpl<SDValue> &InVals) const {
1801  SelectionDAG &DAG = CLI.DAG;
1802  SDLoc &dl = CLI.DL;
1804  SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1806  SDValue Chain = CLI.Chain;
1807  SDValue Callee = CLI.Callee;
1808  bool &isTailCall = CLI.IsTailCall;
1809  CallingConv::ID CallConv = CLI.CallConv;
1810  bool doesNotRet = CLI.DoesNotReturn;
1811  bool isVarArg = CLI.IsVarArg;
1812 
1813  MachineFunction &MF = DAG.getMachineFunction();
1814  bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1815  bool isThisReturn = false;
1816  bool isSibCall = false;
1817  auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
1818 
1819  // Disable tail calls if they're not supported.
1820  if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1821  isTailCall = false;
1822 
1823  if (isTailCall) {
1824  // Check if it's really possible to do a tail call.
1825  isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1826  isVarArg, isStructRet, MF.getFunction().hasStructRetAttr(),
1827  Outs, OutVals, Ins, DAG);
1828  if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
1829  report_fatal_error("failed to perform tail call elimination on a call "
1830  "site marked musttail");
1831  // We don't support GuaranteedTailCallOpt for ARM, only automatically
1832  // detected sibcalls.
1833  if (isTailCall) {
1834  ++NumTailCalls;
1835  isSibCall = true;
1836  }
1837  }
1838 
1839  // Analyze operands of the call, assigning locations to each operand.
1841  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1842  *DAG.getContext());
1843  CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
1844 
1845  // Get a count of how many bytes are to be pushed on the stack.
1846  unsigned NumBytes = CCInfo.getNextStackOffset();
1847 
1848  // For tail calls, memory operands are available in our caller's stack.
1849  if (isSibCall)
1850  NumBytes = 0;
1851 
1852  // Adjust the stack pointer for the new arguments...
1853  // These operations are automatically eliminated by the prolog/epilog pass
1854  if (!isSibCall)
1855  Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
1856 
1857  SDValue StackPtr =
1858  DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1859 
1860  RegsToPassVector RegsToPass;
1861  SmallVector<SDValue, 8> MemOpChains;
1862 
1863  // Walk the register/memloc assignments, inserting copies/loads. In the case
1864  // of tail call optimization, arguments are handled later.
1865  for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1866  i != e;
1867  ++i, ++realArgIdx) {
1868  CCValAssign &VA = ArgLocs[i];
1869  SDValue Arg = OutVals[realArgIdx];
1870  ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1871  bool isByVal = Flags.isByVal();
1872 
1873  // Promote the value if needed.
1874  switch (VA.getLocInfo()) {
1875  default: llvm_unreachable("Unknown loc info!");
1876  case CCValAssign::Full: break;
1877  case CCValAssign::SExt:
1878  Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1879  break;
1880  case CCValAssign::ZExt:
1881  Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1882  break;
1883  case CCValAssign::AExt:
1884  Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1885  break;
1886  case CCValAssign::BCvt:
1887  Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1888  break;
1889  }
1890 
1891  // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1892  if (VA.needsCustom()) {
1893  if (VA.getLocVT() == MVT::v2f64) {
1894  SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1895  DAG.getConstant(0, dl, MVT::i32));
1896  SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1897  DAG.getConstant(1, dl, MVT::i32));
1898 
1899  PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1900  VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1901 
1902  VA = ArgLocs[++i]; // skip ahead to next loc
1903  if (VA.isRegLoc()) {
1904  PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1905  VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1906  } else {
1907  assert(VA.isMemLoc());
1908 
1909  MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1910  dl, DAG, VA, Flags));
1911  }
1912  } else {
1913  PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1914  StackPtr, MemOpChains, Flags);
1915  }
1916  } else if (VA.isRegLoc()) {
1917  if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
1918  Outs[0].VT == MVT::i32) {
1919  assert(VA.getLocVT() == MVT::i32 &&
1920  "unexpected calling convention register assignment");
1921  assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1922  "unexpected use of 'returned'");
1923  isThisReturn = true;
1924  }
1925  RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1926  } else if (isByVal) {
1927  assert(VA.isMemLoc());
1928  unsigned offset = 0;
1929 
1930  // True if this byval aggregate will be split between registers
1931  // and memory.
1932  unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1933  unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1934 
1935  if (CurByValIdx < ByValArgsCount) {
1936 
1937  unsigned RegBegin, RegEnd;
1938  CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1939 
1940  EVT PtrVT =
1942  unsigned int i, j;
1943  for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1944  SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1945  SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1946  SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1948  DAG.InferPtrAlignment(AddArg));
1949  MemOpChains.push_back(Load.getValue(1));
1950  RegsToPass.push_back(std::make_pair(j, Load));
1951  }
1952 
1953  // If parameter size outsides register area, "offset" value
1954  // helps us to calculate stack slot for remained part properly.
1955  offset = RegEnd - RegBegin;
1956 
1957  CCInfo.nextInRegsParam();
1958  }
1959 
1960  if (Flags.getByValSize() > 4*offset) {
1961  auto PtrVT = getPointerTy(DAG.getDataLayout());
1962  unsigned LocMemOffset = VA.getLocMemOffset();
1963  SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1964  SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1965  SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1966  SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1967  SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1968  MVT::i32);
1969  SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1970  MVT::i32);
1971 
1972  SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1973  SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1974  MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1975  Ops));
1976  }
1977  } else if (!isSibCall) {
1978  assert(VA.isMemLoc());
1979 
1980  MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1981  dl, DAG, VA, Flags));
1982  }
1983  }
1984 
1985  if (!MemOpChains.empty())
1986  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1987 
1988  // Build a sequence of copy-to-reg nodes chained together with token chain
1989  // and flag operands which copy the outgoing args into the appropriate regs.
1990  SDValue InFlag;
1991  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1992  Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1993  RegsToPass[i].second, InFlag);
1994  InFlag = Chain.getValue(1);
1995  }
1996 
1997  // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1998  // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1999  // node so that legalize doesn't hack it.
2000  bool isDirect = false;
2001 
2002  const TargetMachine &TM = getTargetMachine();
2003  const Module *Mod = MF.getFunction().getParent();
2004  const GlobalValue *GV = nullptr;
2005  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2006  GV = G->getGlobal();
2007  bool isStub =
2008  !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2009 
2010  bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2011  bool isLocalARMFunc = false;
2013  auto PtrVt = getPointerTy(DAG.getDataLayout());
2014 
2015  if (Subtarget->genLongCalls()) {
2016  assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2017  "long-calls codegen is not position independent!");
2018  // Handle a global address or an external symbol. If it's not one of
2019  // those, the target's already in a register, so we don't need to do
2020  // anything extra.
2021  if (isa<GlobalAddressSDNode>(Callee)) {
2022  // Create a constant pool entry for the callee address
2023  unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2024  ARMConstantPoolValue *CPV =
2025  ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2026 
2027  // Get the address of the callee into a register
2028  SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2029  CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2030  Callee = DAG.getLoad(
2031  PtrVt, dl, DAG.getEntryNode(), CPAddr,
2033  } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2034  const char *Sym = S->getSymbol();
2035 
2036  // Create a constant pool entry for the callee address
2037  unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2038  ARMConstantPoolValue *CPV =
2040  ARMPCLabelIndex, 0);
2041  // Get the address of the callee into a register
2042  SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2043  CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2044  Callee = DAG.getLoad(
2045  PtrVt, dl, DAG.getEntryNode(), CPAddr,
2047  }
2048  } else if (isa<GlobalAddressSDNode>(Callee)) {
2049  // If we're optimizing for minimum size and the function is called three or
2050  // more times in this block, we can improve codesize by calling indirectly
2051  // as BLXr has a 16-bit encoding.
2052  auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2053  auto *BB = CLI.CS.getParent();
2054  bool PreferIndirect =
2055  Subtarget->isThumb() && Subtarget->hasMinSize() &&
2056  count_if(GV->users(), [&BB](const User *U) {
2057  return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
2058  }) > 2;
2059 
2060  if (!PreferIndirect) {
2061  isDirect = true;
2062  bool isDef = GV->isStrongDefinitionForLinker();
2063 
2064  // ARM call to a local ARM function is predicable.
2065  isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2066  // tBX takes a register source operand.
2067  if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2068  assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2069  Callee = DAG.getNode(
2070  ARMISD::WrapperPIC, dl, PtrVt,
2071  DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2072  Callee = DAG.getLoad(
2073  PtrVt, dl, DAG.getEntryNode(), Callee,
2075  /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2077  } else if (Subtarget->isTargetCOFF()) {
2078  assert(Subtarget->isTargetWindows() &&
2079  "Windows is the only supported COFF target");
2080  unsigned TargetFlags = GV->hasDLLImportStorageClass()
2083  Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2084  TargetFlags);
2085  if (GV->hasDLLImportStorageClass())
2086  Callee =
2087  DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2088  DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2090  } else {
2091  Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2092  }
2093  }
2094  } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2095  isDirect = true;
2096  // tBX takes a register source operand.
2097  const char *Sym = S->getSymbol();
2098  if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2099  unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2100  ARMConstantPoolValue *CPV =
2102  ARMPCLabelIndex, 4);
2103  SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2104  CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2105  Callee = DAG.getLoad(
2106  PtrVt, dl, DAG.getEntryNode(), CPAddr,
2108  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2109  Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2110  } else {
2111  Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2112  }
2113  }
2114 
2115  // FIXME: handle tail calls differently.
2116  unsigned CallOpc;
2117  if (Subtarget->isThumb()) {
2118  if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2119  CallOpc = ARMISD::CALL_NOLINK;
2120  else
2121  CallOpc = ARMISD::CALL;
2122  } else {
2123  if (!isDirect && !Subtarget->hasV5TOps())
2124  CallOpc = ARMISD::CALL_NOLINK;
2125  else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2126  // Emit regular call when code size is the priority
2127  !Subtarget->hasMinSize())
2128  // "mov lr, pc; b _foo" to avoid confusing the RSP
2129  CallOpc = ARMISD::CALL_NOLINK;
2130  else
2131  CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2132  }
2133 
2134  std::vector<SDValue> Ops;
2135  Ops.push_back(Chain);
2136  Ops.push_back(Callee);
2137 
2138  // Add argument registers to the end of the list so that they are known live
2139  // into the call.
2140  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2141  Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2142  RegsToPass[i].second.getValueType()));
2143 
2144  // Add a register mask operand representing the call-preserved registers.
2145  if (!isTailCall) {
2146  const uint32_t *Mask;
2147  const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2148  if (isThisReturn) {
2149  // For 'this' returns, use the R0-preserving mask if applicable
2150  Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2151  if (!Mask) {
2152  // Set isThisReturn to false if the calling convention is not one that
2153  // allows 'returned' to be modeled in this way, so LowerCallResult does
2154  // not try to pass 'this' straight through
2155  isThisReturn = false;
2156  Mask = ARI->getCallPreservedMask(MF, CallConv);
2157  }
2158  } else
2159  Mask = ARI->getCallPreservedMask(MF, CallConv);
2160 
2161  assert(Mask && "Missing call preserved mask for calling convention");
2162  Ops.push_back(DAG.getRegisterMask(Mask));
2163  }
2164 
2165  if (InFlag.getNode())
2166  Ops.push_back(InFlag);
2167 
2168  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2169  if (isTailCall) {
2171  return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2172  }
2173 
2174  // Returns a chain and a flag for retval copy to use.
2175  Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2176  InFlag = Chain.getValue(1);
2177 
2178  Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2179  DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2180  if (!Ins.empty())
2181  InFlag = Chain.getValue(1);
2182 
2183  // Handle result values, copying them out of physregs into vregs that we
2184  // return.
2185  return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2186  InVals, isThisReturn,
2187  isThisReturn ? OutVals[0] : SDValue());
2188 }
2189 
2190 /// HandleByVal - Every parameter *after* a byval parameter is passed
2191 /// on the stack. Remember the next parameter register to allocate,
2192 /// and then confiscate the rest of the parameter registers to insure
2193 /// this.
2194 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2195  unsigned Align) const {
2196  // Byval (as with any stack) slots are always at least 4 byte aligned.
2197  Align = std::max(Align, 4U);
2198 
2199  unsigned Reg = State->AllocateReg(GPRArgRegs);
2200  if (!Reg)
2201  return;
2202 
2203  unsigned AlignInRegs = Align / 4;
2204  unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2205  for (unsigned i = 0; i < Waste; ++i)
2206  Reg = State->AllocateReg(GPRArgRegs);
2207 
2208  if (!Reg)
2209  return;
2210 
2211  unsigned Excess = 4 * (ARM::R4 - Reg);
2212 
2213  // Special case when NSAA != SP and parameter size greater than size of
2214  // all remained GPR regs. In that case we can't split parameter, we must
2215  // send it to stack. We also must set NCRN to R4, so waste all
2216  // remained registers.
2217  const unsigned NSAAOffset = State->getNextStackOffset();
2218  if (NSAAOffset != 0 && Size > Excess) {
2219  while (State->AllocateReg(GPRArgRegs))
2220  ;
2221  return;
2222  }
2223 
2224  // First register for byval parameter is the first register that wasn't
2225  // allocated before this method call, so it would be "reg".
2226  // If parameter is small enough to be saved in range [reg, r4), then
2227  // the end (first after last) register would be reg + param-size-in-regs,
2228  // else parameter would be splitted between registers and stack,
2229  // end register would be r4 in this case.
2230  unsigned ByValRegBegin = Reg;
2231  unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2232  State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2233  // Note, first register is allocated in the beginning of function already,
2234  // allocate remained amount of registers we need.
2235  for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2236  State->AllocateReg(GPRArgRegs);
2237  // A byval parameter that is split between registers and memory needs its
2238  // size truncated here.
2239  // In the case where the entire structure fits in registers, we set the
2240  // size in memory to zero.
2241  Size = std::max<int>(Size - Excess, 0);
2242 }
2243 
2244 /// MatchingStackOffset - Return true if the given stack call argument is
2245 /// already available in the same position (relatively) of the caller's
2246 /// incoming argument stack.
2247 static
2250  const TargetInstrInfo *TII) {
2251  unsigned Bytes = Arg.getValueSizeInBits() / 8;
2252  int FI = std::numeric_limits<int>::max();
2253  if (Arg.getOpcode() == ISD::CopyFromReg) {
2254  unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2256  return false;
2257  MachineInstr *Def = MRI->getVRegDef(VR);
2258  if (!Def)
2259  return false;
2260  if (!Flags.isByVal()) {
2261  if (!TII->isLoadFromStackSlot(*Def, FI))
2262  return false;
2263  } else {
2264  return false;
2265  }
2266  } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2267  if (Flags.isByVal())
2268  // ByVal argument is passed in as a pointer but it's now being
2269  // dereferenced. e.g.
2270  // define @foo(%struct.X* %A) {
2271  // tail call @bar(%struct.X* byval %A)
2272  // }
2273  return false;
2274  SDValue Ptr = Ld->getBasePtr();
2275  FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2276  if (!FINode)
2277  return false;
2278  FI = FINode->getIndex();
2279  } else
2280  return false;
2281 
2283  if (!MFI.isFixedObjectIndex(FI))
2284  return false;
2285  return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2286 }
2287 
2288 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2289 /// for tail call optimization. Targets which want to do tail call
2290 /// optimization should implement this function.
2291 bool
2292 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2293  CallingConv::ID CalleeCC,
2294  bool isVarArg,
2295  bool isCalleeStructRet,
2296  bool isCallerStructRet,
2297  const SmallVectorImpl<ISD::OutputArg> &Outs,
2298  const SmallVectorImpl<SDValue> &OutVals,
2299  const SmallVectorImpl<ISD::InputArg> &Ins,
2300  SelectionDAG& DAG) const {
2301  MachineFunction &MF = DAG.getMachineFunction();
2302  const Function &CallerF = MF.getFunction();
2303  CallingConv::ID CallerCC = CallerF.getCallingConv();
2304 
2305  assert(Subtarget->supportsTailCall());
2306 
2307  // Tail calls to function pointers cannot be optimized for Thumb1 if the args
2308  // to the call take up r0-r3. The reason is that there are no legal registers
2309  // left to hold the pointer to the function to be called.
2310  if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2311  !isa<GlobalAddressSDNode>(Callee.getNode()))
2312  return false;
2313 
2314  // Look for obvious safe cases to perform tail call optimization that do not
2315  // require ABI changes. This is what gcc calls sibcall.
2316 
2317  // Exception-handling functions need a special set of instructions to indicate
2318  // a return to the hardware. Tail-calling another function would probably
2319  // break this.
2320  if (CallerF.hasFnAttribute("interrupt"))
2321  return false;
2322 
2323  // Also avoid sibcall optimization if either caller or callee uses struct
2324  // return semantics.
2325  if (isCalleeStructRet || isCallerStructRet)
2326  return false;
2327 
2328  // Externally-defined functions with weak linkage should not be
2329  // tail-called on ARM when the OS does not support dynamic
2330  // pre-emption of symbols, as the AAELF spec requires normal calls
2331  // to undefined weak functions to be replaced with a NOP or jump to the
2332  // next instruction. The behaviour of branch instructions in this
2333  // situation (as used for tail calls) is implementation-defined, so we
2334  // cannot rely on the linker replacing the tail call with a return.
2335  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2336  const GlobalValue *GV = G->getGlobal();
2337  const Triple &TT = getTargetMachine().getTargetTriple();
2338  if (GV->hasExternalWeakLinkage() &&
2339  (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2340  return false;
2341  }
2342 
2343  // Check that the call results are passed in the same way.
2344  LLVMContext &C = *DAG.getContext();
2345  if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2346  CCAssignFnForReturn(CalleeCC, isVarArg),
2347  CCAssignFnForReturn(CallerCC, isVarArg)))
2348  return false;
2349  // The callee has to preserve all registers the caller needs to preserve.
2350  const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2351  const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2352  if (CalleeCC != CallerCC) {
2353  const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2354  if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2355  return false;
2356  }
2357 
2358  // If Caller's vararg or byval argument has been split between registers and
2359  // stack, do not perform tail call, since part of the argument is in caller's
2360  // local frame.
2361  const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2362  if (AFI_Caller->getArgRegsSaveSize())
2363  return false;
2364 
2365  // If the callee takes no arguments then go on to check the results of the
2366  // call.
2367  if (!Outs.empty()) {
2368  // Check if stack adjustment is needed. For now, do not do this if any
2369  // argument is passed on the stack.
2371  CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2372  CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2373  if (CCInfo.getNextStackOffset()) {
2374  // Check if the arguments are already laid out in the right way as
2375  // the caller's fixed stack objects.
2376  MachineFrameInfo &MFI = MF.getFrameInfo();
2377  const MachineRegisterInfo *MRI = &MF.getRegInfo();
2378  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2379  for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2380  i != e;
2381  ++i, ++realArgIdx) {
2382  CCValAssign &VA = ArgLocs[i];
2383  EVT RegVT = VA.getLocVT();
2384  SDValue Arg = OutVals[realArgIdx];
2385  ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2386  if (VA.getLocInfo() == CCValAssign::Indirect)
2387  return false;
2388  if (VA.needsCustom()) {
2389  // f64 and vector types are split into multiple registers or
2390  // register/stack-slot combinations. The types will not match
2391  // the registers; give up on memory f64 refs until we figure
2392  // out what to do about this.
2393  if (!VA.isRegLoc())
2394  return false;
2395  if (!ArgLocs[++i].isRegLoc())
2396  return false;
2397  if (RegVT == MVT::v2f64) {
2398  if (!ArgLocs[++i].isRegLoc())
2399  return false;
2400  if (!ArgLocs[++i].isRegLoc())
2401  return false;
2402  }
2403  } else if (!VA.isRegLoc()) {
2404  if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2405  MFI, MRI, TII))
2406  return false;
2407  }
2408  }
2409  }
2410 
2411  const MachineRegisterInfo &MRI = MF.getRegInfo();
2412  if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2413  return false;
2414  }
2415 
2416  return true;
2417 }
2418 
2419 bool
2420 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2421  MachineFunction &MF, bool isVarArg,
2422  const SmallVectorImpl<ISD::OutputArg> &Outs,
2423  LLVMContext &Context) const {
2425  CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2426  return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2427 }
2428 
2430  const SDLoc &DL, SelectionDAG &DAG) {
2431  const MachineFunction &MF = DAG.getMachineFunction();
2432  const Function &F = MF.getFunction();
2433 
2434  StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2435 
2436  // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2437  // version of the "preferred return address". These offsets affect the return
2438  // instruction if this is a return from PL1 without hypervisor extensions.
2439  // IRQ/FIQ: +4 "subs pc, lr, #4"
2440  // SWI: 0 "subs pc, lr, #0"
2441  // ABORT: +4 "subs pc, lr, #4"
2442  // UNDEF: +4/+2 "subs pc, lr, #0"
2443  // UNDEF varies depending on where the exception came from ARM or Thumb
2444  // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2445 
2446  int64_t LROffset;
2447  if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2448  IntKind == "ABORT")
2449  LROffset = 4;
2450  else if (IntKind == "SWI" || IntKind == "UNDEF")
2451  LROffset = 0;
2452  else
2453  report_fatal_error("Unsupported interrupt attribute. If present, value "
2454  "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2455 
2456  RetOps.insert(RetOps.begin() + 1,
2457  DAG.getConstant(LROffset, DL, MVT::i32, false));
2458 
2459  return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2460 }
2461 
2462 SDValue
2463 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2464  bool isVarArg,
2465  const SmallVectorImpl<ISD::OutputArg> &Outs,
2466  const SmallVectorImpl<SDValue> &OutVals,
2467  const SDLoc &dl, SelectionDAG &DAG) const {
2468  // CCValAssign - represent the assignment of the return value to a location.
2470 
2471  // CCState - Info about the registers and stack slots.
2472  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2473  *DAG.getContext());
2474 
2475  // Analyze outgoing return values.
2476  CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2477 
2478  SDValue Flag;
2479  SmallVector<SDValue, 4> RetOps;
2480  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2481  bool isLittleEndian = Subtarget->isLittle();
2482 
2483  MachineFunction &MF = DAG.getMachineFunction();
2485  AFI->setReturnRegsCount(RVLocs.size());
2486 
2487  // Copy the result values into the output registers.
2488  for (unsigned i = 0, realRVLocIdx = 0;
2489  i != RVLocs.size();
2490  ++i, ++realRVLocIdx) {
2491  CCValAssign &VA = RVLocs[i];
2492  assert(VA.isRegLoc() && "Can only return in registers!");
2493 
2494  SDValue Arg = OutVals[realRVLocIdx];
2495  bool ReturnF16 = false;
2496 
2497  if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2498  // Half-precision return values can be returned like this:
2499  //
2500  // t11 f16 = fadd ...
2501  // t12: i16 = bitcast t11
2502  // t13: i32 = zero_extend t12
2503  // t14: f32 = bitcast t13 <~~~~~~~ Arg
2504  //
2505  // to avoid code generation for bitcasts, we simply set Arg to the node
2506  // that produces the f16 value, t11 in this case.
2507  //
2508  if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2509  SDValue ZE = Arg.getOperand(0);
2510  if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2511  SDValue BC = ZE.getOperand(0);
2512  if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2513  Arg = BC.getOperand(0);
2514  ReturnF16 = true;
2515  }
2516  }
2517  }
2518  }
2519 
2520  switch (VA.getLocInfo()) {
2521  default: llvm_unreachable("Unknown loc info!");
2522  case CCValAssign::Full: break;
2523  case CCValAssign::BCvt:
2524  if (!ReturnF16)
2525  Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2526  break;
2527  }
2528 
2529  if (VA.needsCustom()) {
2530  if (VA.getLocVT() == MVT::v2f64) {
2531  // Extract the first half and return it in two registers.
2532  SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2533  DAG.getConstant(0, dl, MVT::i32));
2534  SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2535  DAG.getVTList(MVT::i32, MVT::i32), Half);
2536 
2537  Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2538  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2539  Flag);
2540  Flag = Chain.getValue(1);
2541  RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2542  VA = RVLocs[++i]; // skip ahead to next loc
2543  Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2544  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2545  Flag);
2546  Flag = Chain.getValue(1);
2547  RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2548  VA = RVLocs[++i]; // skip ahead to next loc
2549 
2550  // Extract the 2nd half and fall through to handle it as an f64 value.
2551  Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2552  DAG.getConstant(1, dl, MVT::i32));
2553  }
2554  // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2555  // available.
2556  SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2557  DAG.getVTList(MVT::i32, MVT::i32), Arg);
2558  Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2559  fmrrd.getValue(isLittleEndian ? 0 : 1),
2560  Flag);
2561  Flag = Chain.getValue(1);
2562  RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2563  VA = RVLocs[++i]; // skip ahead to next loc
2564  Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2565  fmrrd.getValue(isLittleEndian ? 1 : 0),
2566  Flag);
2567  } else
2568  Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2569 
2570  // Guarantee that all emitted copies are
2571  // stuck together, avoiding something bad.
2572  Flag = Chain.getValue(1);
2573  RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2574  ReturnF16 ? MVT::f16 : VA.getLocVT()));
2575  }
2576  const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2577  const MCPhysReg *I =
2579  if (I) {
2580  for (; *I; ++I) {
2581  if (ARM::GPRRegClass.contains(*I))
2582  RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2583  else if (ARM::DPRRegClass.contains(*I))
2584  RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2585  else
2586  llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2587  }
2588  }
2589 
2590  // Update chain and glue.
2591  RetOps[0] = Chain;
2592  if (Flag.getNode())
2593  RetOps.push_back(Flag);
2594 
2595  // CPUs which aren't M-class use a special sequence to return from
2596  // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2597  // though we use "subs pc, lr, #N").
2598  //
2599  // M-class CPUs actually use a normal return sequence with a special
2600  // (hardware-provided) value in LR, so the normal code path works.
2601  if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2602  !Subtarget->isMClass()) {
2603  if (Subtarget->isThumb1Only())
2604  report_fatal_error("interrupt attribute is not supported in Thumb1");
2605  return LowerInterruptReturn(RetOps, dl, DAG);
2606  }
2607 
2608  return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2609 }
2610 
2611 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2612  if (N->getNumValues() != 1)
2613  return false;
2614  if (!N->hasNUsesOfValue(1, 0))
2615  return false;
2616 
2617  SDValue TCChain = Chain;
2618  SDNode *Copy = *N->use_begin();
2619  if (Copy->getOpcode() == ISD::CopyToReg) {
2620  // If the copy has a glue operand, we conservatively assume it isn't safe to
2621  // perform a tail call.
2622  if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2623  return false;
2624  TCChain = Copy->getOperand(0);
2625  } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2626  SDNode *VMov = Copy;
2627  // f64 returned in a pair of GPRs.
2629  for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2630  UI != UE; ++UI) {
2631  if (UI->getOpcode() != ISD::CopyToReg)
2632  return false;
2633  Copies.insert(*UI);
2634  }
2635  if (Copies.size() > 2)
2636  return false;
2637 
2638  for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2639  UI != UE; ++UI) {
2640  SDValue UseChain = UI->getOperand(0);
2641  if (Copies.count(UseChain.getNode()))
2642  // Second CopyToReg
2643  Copy = *UI;
2644  else {
2645  // We are at the top of this chain.
2646  // If the copy has a glue operand, we conservatively assume it
2647  // isn't safe to perform a tail call.
2648  if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2649  return false;
2650  // First CopyToReg
2651  TCChain = UseChain;
2652  }
2653  }
2654  } else if (Copy->getOpcode() == ISD::BITCAST) {
2655  // f32 returned in a single GPR.
2656  if (!Copy->hasOneUse())
2657  return false;
2658  Copy = *Copy->use_begin();
2659  if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2660  return false;
2661  // If the copy has a glue operand, we conservatively assume it isn't safe to
2662  // perform a tail call.
2663  if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2664  return false;
2665  TCChain = Copy->getOperand(0);
2666  } else {
2667  return false;
2668  }
2669 
2670  bool HasRet = false;
2671  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2672  UI != UE; ++UI) {
2673  if (UI->getOpcode() != ARMISD::RET_FLAG &&
2674  UI->getOpcode() != ARMISD::INTRET_FLAG)
2675  return false;
2676  HasRet = true;
2677  }
2678 
2679  if (!HasRet)
2680  return false;
2681 
2682  Chain = TCChain;
2683  return true;
2684 }
2685 
2686 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2687  if (!Subtarget->supportsTailCall())
2688  return false;
2689 
2690  auto Attr =
2691  CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2692  if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2693  return false;
2694 
2695  return true;
2696 }
2697 
2698 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2699 // and pass the lower and high parts through.
2701  SDLoc DL(Op);
2702  SDValue WriteValue = Op->getOperand(2);
2703 
2704  // This function is only supposed to be called for i64 type argument.
2705  assert(WriteValue.getValueType() == MVT::i64
2706  && "LowerWRITE_REGISTER called for non-i64 type argument.");
2707 
2708  SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2709  DAG.getConstant(0, DL, MVT::i32));
2710  SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2711  DAG.getConstant(1, DL, MVT::i32));
2712  SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2713  return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2714 }
2715 
2716 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2717 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2718 // one of the above mentioned nodes. It has to be wrapped because otherwise
2719 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2720 // be used to form addressing mode. These wrapped nodes will be selected
2721 // into MOVi.
2722 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2723  SelectionDAG &DAG) const {
2724  EVT PtrVT = Op.getValueType();
2725  // FIXME there is no actual debug info here
2726  SDLoc dl(Op);
2727  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2728  SDValue Res;
2729 
2730  // When generating execute-only code Constant Pools must be promoted to the
2731  // global data section. It's a bit ugly that we can't share them across basic
2732  // blocks, but this way we guarantee that execute-only behaves correct with
2733  // position-independent addressing modes.
2734  if (Subtarget->genExecuteOnly()) {
2735  auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2736  auto T = const_cast<Type*>(CP->getType());
2737  auto C = const_cast<Constant*>(CP->getConstVal());
2738  auto M = const_cast<Module*>(DAG.getMachineFunction().
2739  getFunction().getParent());
2740  auto GV = new GlobalVariable(
2741  *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C,
2742  Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2743  Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2744  Twine(AFI->createPICLabelUId())
2745  );
2746  SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2747  dl, PtrVT);
2748  return LowerGlobalAddress(GA, DAG);
2749  }
2750 
2751  if (CP->isMachineConstantPoolEntry())
2752  Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2753  CP->getAlignment());
2754  else
2755  Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2756  CP->getAlignment());
2757  return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2758 }
2759 
2762 }
2763 
2764 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2765  SelectionDAG &DAG) const {
2766  MachineFunction &MF = DAG.getMachineFunction();
2768  unsigned ARMPCLabelIndex = 0;
2769  SDLoc DL(Op);
2770  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2771  const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2772  SDValue CPAddr;
2773  bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2774  if (!IsPositionIndependent) {
2775  CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2776  } else {
2777  unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2778  ARMPCLabelIndex = AFI->createPICLabelUId();
2779  ARMConstantPoolValue *CPV =
2780  ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2781  ARMCP::CPBlockAddress, PCAdj);
2782  CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2783  }
2784  CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2785  SDValue Result = DAG.getLoad(
2786  PtrVT, DL, DAG.getEntryNode(), CPAddr,
2788  if (!IsPositionIndependent)
2789  return Result;
2790  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2791  return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2792 }
2793 
2794 /// Convert a TLS address reference into the correct sequence of loads
2795 /// and calls to compute the variable's address for Darwin, and return an
2796 /// SDValue containing the final node.
2797 
2798 /// Darwin only has one TLS scheme which must be capable of dealing with the
2799 /// fully general situation, in the worst case. This means:
2800 /// + "extern __thread" declaration.
2801 /// + Defined in a possibly unknown dynamic library.
2802 ///
2803 /// The general system is that each __thread variable has a [3 x i32] descriptor
2804 /// which contains information used by the runtime to calculate the address. The
2805 /// only part of this the compiler needs to know about is the first word, which
2806 /// contains a function pointer that must be called with the address of the
2807 /// entire descriptor in "r0".
2808 ///
2809 /// Since this descriptor may be in a different unit, in general access must
2810 /// proceed along the usual ARM rules. A common sequence to produce is:
2811 ///
2812 /// movw rT1, :lower16:_var$non_lazy_ptr
2813 /// movt rT1, :upper16:_var$non_lazy_ptr
2814 /// ldr r0, [rT1]
2815 /// ldr rT2, [r0]
2816 /// blx rT2
2817 /// [...address now in r0...]
2818 SDValue
2819 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2820  SelectionDAG &DAG) const {
2821  assert(Subtarget->isTargetDarwin() &&
2822  "This function expects a Darwin target");
2823  SDLoc DL(Op);
2824 
2825  // First step is to get the address of the actua global symbol. This is where
2826  // the TLS descriptor lives.
2827  SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2828 
2829  // The first entry in the descriptor is a function pointer that we must call
2830  // to obtain the address of the variable.
2831  SDValue Chain = DAG.getEntryNode();
2832  SDValue FuncTLVGet = DAG.getLoad(
2833  MVT::i32, DL, Chain, DescAddr,
2835  /* Alignment = */ 4,
2838  Chain = FuncTLVGet.getValue(1);
2839 
2841  MachineFrameInfo &MFI = F.getFrameInfo();
2842  MFI.setAdjustsStack(true);
2843 
2844  // TLS calls preserve all registers except those that absolutely must be
2845  // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2846  // silly).
2847  auto TRI =
2848  getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
2849  auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2850  const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2851 
2852  // Finally, we can make the call. This is just a degenerate version of a
2853  // normal AArch64 call node: r0 takes the address of the descriptor, and
2854  // returns the address of the variable in this thread.
2855  Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2856  Chain =
2858  Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2859  DAG.getRegisterMask(Mask), Chain.getValue(1));
2860  return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2861 }
2862 
2863 SDValue
2864 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2865  SelectionDAG &DAG) const {
2866  assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2867 
2868  SDValue Chain = DAG.getEntryNode();
2869  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2870  SDLoc DL(Op);
2871 
2872  // Load the current TEB (thread environment block)
2873  SDValue Ops[] = {Chain,
2874  DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2875  DAG.getConstant(15, DL, MVT::i32),
2876  DAG.getConstant(0, DL, MVT::i32),
2877  DAG.getConstant(13, DL, MVT::i32),
2878  DAG.getConstant(0, DL, MVT::i32),
2879  DAG.getConstant(2, DL, MVT::i32)};
2880  SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2881  DAG.getVTList(MVT::i32, MVT::Other), Ops);
2882 
2883  SDValue TEB = CurrentTEB.getValue(0);
2884  Chain = CurrentTEB.getValue(1);
2885 
2886  // Load the ThreadLocalStoragePointer from the TEB
2887  // A pointer to the TLS array is located at offset 0x2c from the TEB.
2888  SDValue TLSArray =
2889  DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2890  TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2891 
2892  // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2893  // offset into the TLSArray.
2894 
2895  // Load the TLS index from the C runtime
2896  SDValue TLSIndex =
2897  DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2898  TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2899  TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2900 
2901  SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2902  DAG.getConstant(2, DL, MVT::i32));
2903  SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2904  DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2905  MachinePointerInfo());
2906 
2907  // Get the offset of the start of the .tls section (section base)
2908  const auto *GA = cast<GlobalAddressSDNode>(Op);
2909  auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2910  SDValue Offset = DAG.getLoad(
2911  PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2912  DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2914 
2915  return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2916 }
2917 
2918 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2919 SDValue
2920 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2921  SelectionDAG &DAG) const {
2922  SDLoc dl(GA);
2923  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2924  unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2925  MachineFunction &MF = DAG.getMachineFunction();
2927  unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2928  ARMConstantPoolValue *CPV =
2929  ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2930  ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2931  SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2932  Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2933  Argument = DAG.getLoad(
2934  PtrVT, dl, DAG.getEntryNode(), Argument,
2936  SDValue Chain = Argument.getValue(1);
2937 
2938  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2939  Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2940 
2941  // call __tls_get_addr.
2942  ArgListTy Args;
2944  Entry.Node = Argument;
2945  Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2946  Args.push_back(Entry);
2947 
2948  // FIXME: is there useful debug info available here?
2950  CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2952  DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2953 
2954  std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2955  return CallResult.first;
2956 }
2957 
2958 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2959 // "local exec" model.
2960 SDValue
2961 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2962  SelectionDAG &DAG,
2963  TLSModel::Model model) const {
2964  const GlobalValue *GV = GA->getGlobal();
2965  SDLoc dl(GA);
2966  SDValue Offset;
2967  SDValue Chain = DAG.getEntryNode();
2968  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2969  // Get the Thread Pointer
2971 
2972  if (model == TLSModel::InitialExec) {
2973  MachineFunction &MF = DAG.getMachineFunction();
2975  unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2976  // Initial exec model.
2977  unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2978  ARMConstantPoolValue *CPV =
2979  ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2981  true);
2982  Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2983  Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2984  Offset = DAG.getLoad(
2985  PtrVT, dl, Chain, Offset,
2987  Chain = Offset.getValue(1);
2988 
2989  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2990  Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2991 
2992  Offset = DAG.getLoad(
2993  PtrVT, dl, Chain, Offset,
2995  } else {
2996  // local exec model
2997  assert(model == TLSModel::LocalExec);
2998  ARMConstantPoolValue *CPV =
3000  Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3001  Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3002  Offset = DAG.getLoad(
3003  PtrVT, dl, Chain, Offset,
3005  }
3006 
3007  // The address of the thread local variable is the add of the thread
3008  // pointer with the offset of the variable.
3009  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3010 }
3011 
3012 SDValue
3013 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3014  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3015  if (DAG.getTarget().useEmulatedTLS())
3016  return LowerToTLSEmulatedModel(GA, DAG);
3017 
3018  if (Subtarget->isTargetDarwin())
3019  return LowerGlobalTLSAddressDarwin(Op, DAG);
3020 
3021  if (Subtarget->isTargetWindows())
3022  return LowerGlobalTLSAddressWindows(Op, DAG);
3023 
3024  // TODO: implement the "local dynamic" model
3025  assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3027 
3028  switch (model) {
3031  return LowerToTLSGeneralDynamicModel(GA, DAG);
3032  case TLSModel::InitialExec:
3033  case TLSModel::LocalExec:
3034  return LowerToTLSExecModels(GA, DAG, model);
3035  }
3036  llvm_unreachable("bogus TLS model");
3037 }
3038 
3039 /// Return true if all users of V are within function F, looking through
3040 /// ConstantExprs.
3041 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3042  SmallVector<const User*,4> Worklist;
3043  for (auto *U : V->users())
3044  Worklist.push_back(U);
3045  while (!Worklist.empty()) {
3046  auto *U = Worklist.pop_back_val();
3047  if (isa<ConstantExpr>(U)) {
3048  for (auto *UU : U->users())
3049  Worklist.push_back(UU);
3050  continue;
3051  }
3052 
3053  auto *I = dyn_cast<Instruction>(U);
3054  if (!I || I->getParent()->getParent() != F)
3055  return false;
3056  }
3057  return true;
3058 }
3059 
3061  const GlobalValue *GV, SelectionDAG &DAG,
3062  EVT PtrVT, const SDLoc &dl) {
3063  // If we're creating a pool entry for a constant global with unnamed address,
3064  // and the global is small enough, we can emit it inline into the constant pool
3065  // to save ourselves an indirection.
3066  //
3067  // This is a win if the constant is only used in one function (so it doesn't
3068  // need to be duplicated) or duplicating the constant wouldn't increase code
3069  // size (implying the constant is no larger than 4 bytes).
3070  const Function &F = DAG.getMachineFunction().getFunction();
3071 
3072  // We rely on this decision to inline being idemopotent and unrelated to the
3073  // use-site. We know that if we inline a variable at one use site, we'll
3074  // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3075  // doesn't know about this optimization, so bail out if it's enabled else
3076  // we could decide to inline here (and thus never emit the GV) but require
3077  // the GV from fast-isel generated code.
3078  if (!EnableConstpoolPromotion ||
3080  return SDValue();
3081 
3082  auto *GVar = dyn_cast<GlobalVariable>(GV);
3083  if (!GVar || !GVar->hasInitializer() ||
3084  !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3085  !GVar->hasLocalLinkage())
3086  return SDValue();
3087 
3088  // If we inline a value that contains relocations, we move the relocations
3089  // from .data to .text. This is not allowed in position-independent code.
3090  auto *Init = GVar->getInitializer();
3091  if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3092  Init->needsRelocation())
3093  return SDValue();
3094 
3095  // The constant islands pass can only really deal with alignment requests
3096  // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3097  // any type wanting greater alignment requirements than 4 bytes. We also
3098  // can only promote constants that are multiples of 4 bytes in size or
3099  // are paddable to a multiple of 4. Currently we only try and pad constants
3100  // that are strings for simplicity.
3101  auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3102  unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3103  unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar);
3104  unsigned RequiredPadding = 4 - (Size % 4);
3105  bool PaddingPossible =
3106  RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3107  if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3108  Size == 0)
3109  return SDValue();
3110 
3111  unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3112  MachineFunction &MF = DAG.getMachineFunction();
3114 
3115  // We can't bloat the constant pool too much, else the ConstantIslands pass
3116  // may fail to converge. If we haven't promoted this global yet (it may have
3117  // multiple uses), and promoting it would increase the constant pool size (Sz
3118  // > 4), ensure we have space to do so up to MaxTotal.
3119  if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3120  if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3122  return SDValue();
3123 
3124  // This is only valid if all users are in a single function; we can't clone
3125  // the constant in general. The LLVM IR unnamed_addr allows merging
3126  // constants, but not cloning them.
3127  //
3128  // We could potentially allow cloning if we could prove all uses of the
3129  // constant in the current function don't care about the address, like
3130  // printf format strings. But that isn't implemented for now.
3131  if (!allUsersAreInFunction(GVar, &F))
3132  return SDValue();
3133 
3134  // We're going to inline this global. Pad it out if needed.
3135  if (RequiredPadding != 4) {
3136  StringRef S = CDAInit->getAsString();
3137 
3139  std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3140  while (RequiredPadding--)
3141  V.push_back(0);
3142  Init = ConstantDataArray::get(*DAG.getContext(), V);
3143  }
3144 
3145  auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3146  SDValue CPAddr =
3147  DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3148  if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3151  PaddedSize - 4);
3152  }
3153  ++NumConstpoolPromoted;
3154  return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3155 }
3156 
3158  if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3159  if (!(GV = GA->getBaseObject()))
3160  return false;
3161  if (const auto *V = dyn_cast<GlobalVariable>(GV))
3162  return V->isConstant();
3163  return isa<Function>(GV);
3164 }
3165 
3166 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3167  SelectionDAG &DAG) const {
3168  switch (Subtarget->getTargetTriple().getObjectFormat()) {
3169  default: llvm_unreachable("unknown object format");
3170  case Triple::COFF:
3171  return LowerGlobalAddressWindows(Op, DAG);
3172  case Triple::ELF:
3173  return LowerGlobalAddressELF(Op, DAG);
3174  case Triple::MachO:
3175  return LowerGlobalAddressDarwin(Op, DAG);
3176  }
3177 }
3178 
3179 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3180  SelectionDAG &DAG) const {
3181  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3182  SDLoc dl(Op);
3183  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3184  const TargetMachine &TM = getTargetMachine();
3185  bool IsRO = isReadOnly(GV);
3186 
3187  // promoteToConstantPool only if not generating XO text section
3188  if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3189  if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3190  return V;
3191 
3192  if (isPositionIndependent()) {
3193  bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3194  SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3195  UseGOT_PREL ? ARMII::MO_GOT : 0);
3196  SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3197  if (UseGOT_PREL)
3198  Result =
3199  DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3201  return Result;
3202  } else if (Subtarget->isROPI() && IsRO) {
3203  // PC-relative.
3204  SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3205  SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3206  return Result;
3207  } else if (Subtarget->isRWPI() && !IsRO) {
3208  // SB-relative.
3209  SDValue RelAddr;
3210  if (Subtarget->useMovt()) {
3211  ++NumMovwMovt;
3212  SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3213  RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3214  } else { // use literal pool for address constant
3215  ARMConstantPoolValue *CPV =
3217  SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3218  CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3219  RelAddr = DAG.getLoad(
3220  PtrVT, dl, DAG.getEntryNode(), CPAddr,
3222  }
3223  SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3224  SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3225  return Result;
3226  }
3227 
3228  // If we have T2 ops, we can materialize the address directly via movt/movw
3229  // pair. This is always cheaper.
3230  if (Subtarget->useMovt()) {
3231  ++NumMovwMovt;
3232  // FIXME: Once remat is capable of dealing with instructions with register
3233  // operands, expand this into two nodes.
3234  return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3235  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3236  } else {
3237  SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3238  CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3239  return DAG.getLoad(
3240  PtrVT, dl, DAG.getEntryNode(), CPAddr,
3242  }
3243 }
3244 
3245 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3246  SelectionDAG &DAG) const {
3247  assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3248  "ROPI/RWPI not currently supported for Darwin");
3249  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3250  SDLoc dl(Op);
3251  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3252 
3253  if (Subtarget->useMovt())
3254  ++NumMovwMovt;
3255 
3256  // FIXME: Once remat is capable of dealing with instructions with register
3257  // operands, expand this into multiple nodes
3258  unsigned Wrapper =
3260 
3261  SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3262  SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3263 
3264  if (Subtarget->isGVIndirectSymbol(GV))
3265  Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3267  return Result;
3268 }
3269 
3270 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3271  SelectionDAG &DAG) const {
3272  assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3273  assert(Subtarget->useMovt() &&
3274  "Windows on ARM expects to use movw/movt");
3275  assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3276  "ROPI/RWPI not currently supported for Windows");
3277 
3278  const TargetMachine &TM = getTargetMachine();
3279  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3281  if (GV->hasDLLImportStorageClass())
3282  TargetFlags = ARMII::MO_DLLIMPORT;
3283  else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3284  TargetFlags = ARMII::MO_COFFSTUB;
3285  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3286  SDValue Result;
3287  SDLoc DL(Op);
3288 
3289  ++NumMovwMovt;
3290 
3291  // FIXME: Once remat is capable of dealing with instructions with register
3292  // operands, expand this into two nodes.
3293  Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3294  DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3295  TargetFlags));
3296  if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3297  Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3299  return Result;
3300 }
3301 
3302 SDValue
3303 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3304  SDLoc dl(Op);
3305  SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3306  return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3307  DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3308  Op.getOperand(1), Val);
3309 }
3310 
3311 SDValue
3312 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3313  SDLoc dl(Op);
3314  return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3315  Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3316 }
3317 
3318 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3319  SelectionDAG &DAG) const {
3320  SDLoc dl(Op);
3322  Op.getOperand(0));
3323 }
3324 
3325 SDValue
3326 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3327  const ARMSubtarget *Subtarget) const {
3328  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3329  SDLoc dl(Op);
3330  switch (IntNo) {
3331  default: return SDValue(); // Don't custom lower most intrinsics.
3332  case Intrinsic::thread_pointer: {
3333  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3334  return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3335  }
3336  case Intrinsic::eh_sjlj_lsda: {
3337  MachineFunction &MF = DAG.getMachineFunction();
3339  unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3340  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3341  SDValue CPAddr;
3342  bool IsPositionIndependent = isPositionIndependent();
3343  unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3344  ARMConstantPoolValue *CPV =
3345  ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3346  ARMCP::CPLSDA, PCAdj);
3347  CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3348  CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3349  SDValue Result = DAG.getLoad(
3350  PtrVT, dl, DAG.getEntryNode(), CPAddr,
3352 
3353  if (IsPositionIndependent) {
3354  SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3355  Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3356  }
3357  return Result;
3358  }
3359  case Intrinsic::arm_neon_vabs:
3360  return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3361  Op.getOperand(1));
3362  case Intrinsic::arm_neon_vmulls:
3363  case Intrinsic::arm_neon_vmullu: {
3364  unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3366  return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3367  Op.getOperand(1), Op.getOperand(2));
3368  }
3369  case Intrinsic::arm_neon_vminnm:
3370  case Intrinsic::arm_neon_vmaxnm: {
3371  unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3373  return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3374  Op.getOperand(1), Op.getOperand(2));
3375  }
3376  case Intrinsic::arm_neon_vminu:
3377  case Intrinsic::arm_neon_vmaxu: {
3378  if (Op.getValueType().isFloatingPoint())
3379  return SDValue();
3380  unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3381  ? ISD::UMIN : ISD::UMAX;
3382  return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3383  Op.getOperand(1), Op.getOperand(2));
3384  }
3385  case Intrinsic::arm_neon_vmins:
3386  case Intrinsic::arm_neon_vmaxs: {
3387  // v{min,max}s is overloaded between signed integers and floats.
3388  if (!Op.getValueType().isFloatingPoint()) {
3389  unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3390  ? ISD::SMIN : ISD::SMAX;
3391  return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3392  Op.getOperand(1), Op.getOperand(2));
3393  }
3394  unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3396  return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3397  Op.getOperand(1), Op.getOperand(2));
3398  }
3399  case Intrinsic::arm_neon_vtbl1:
3400  return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3401  Op.getOperand(1), Op.getOperand(2));
3402  case Intrinsic::arm_neon_vtbl2:
3403  return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3404  Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3405  }
3406 }
3407 
3409  const ARMSubtarget *Subtarget) {
3410  SDLoc dl(Op);
3411  ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3412  auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3413  if (SSID == SyncScope::SingleThread)
3414  return Op;
3415 
3416  if (!Subtarget->hasDataBarrier()) {
3417  // Some ARMv6 cpus can support data barriers with an mcr instruction.
3418  // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3419  // here.
3420  assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3421  "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3422  return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3423  DAG.getConstant(0, dl, MVT::i32));
3424  }
3425 
3426  ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3427  AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3428  ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3429  if (Subtarget->isMClass()) {
3430  // Only a full system barrier exists in the M-class architectures.
3431  Domain = ARM_MB::SY;
3432  } else if (Subtarget->preferISHSTBarriers() &&
3433  Ord == AtomicOrdering::Release) {
3434  // Swift happens to implement ISHST barriers in a way that's compatible with
3435  // Release semantics but weaker than ISH so we'd be fools not to use
3436  // it. Beware: other processors probably don't!
3437  Domain = ARM_MB::ISHST;
3438  }
3439 
3440  return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3441  DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3442  DAG.getConstant(Domain, dl, MVT::i32));
3443 }
3444 
3446  const ARMSubtarget *Subtarget) {
3447  // ARM pre v5TE and Thumb1 does not have preload instructions.
3448  if (!(Subtarget->isThumb2() ||
3449  (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3450  // Just preserve the chain.
3451  return Op.getOperand(0);
3452 
3453  SDLoc dl(Op);
3454  unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3455  if (!isRead &&
3456  (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3457  // ARMv7 with MP extension has PLDW.
3458  return Op.getOperand(0);
3459 
3460  unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3461  if (Subtarget->isThumb()) {
3462  // Invert the bits.
3463  isRead = ~isRead & 1;
3464  isData = ~isData & 1;
3465  }
3466 
3467  return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3468  Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3469  DAG.getConstant(isData, dl, MVT::i32));
3470 }
3471 
3473  MachineFunction &MF = DAG.getMachineFunction();
3474  ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3475 
3476  // vastart just stores the address of the VarArgsFrameIndex slot into the
3477  // memory location argument.
3478  SDLoc dl(Op);
3479  EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3480  SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3481  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3482  return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3483  MachinePointerInfo(SV));
3484 }
3485 
3486 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3487  CCValAssign &NextVA,
3488  SDValue &Root,
3489  SelectionDAG &DAG,
3490  const SDLoc &dl) const {
3491  MachineFunction &MF = DAG.getMachineFunction();
3493 
3494  const TargetRegisterClass *RC;
3495  if (AFI->isThumb1OnlyFunction())
3496  RC = &ARM::tGPRRegClass;
3497  else
3498  RC = &ARM::GPRRegClass;
3499 
3500  // Transform the arguments stored in physical registers into virtual ones.
3501  unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3502  SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3503 
3504  SDValue ArgValue2;
3505  if (NextVA.isMemLoc()) {
3506  MachineFrameInfo &MFI = MF.getFrameInfo();
3507  int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3508 
3509  // Create load node to retrieve arguments from the stack.
3510  SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3511  ArgValue2 = DAG.getLoad(
3512  MVT::i32, dl, Root, FIN,
3514  } else {
3515  Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3516  ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3517  }
3518  if (!Subtarget->isLittle())
3519  std::swap (ArgValue, ArgValue2);
3520  return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3521 }
3522 
3523 // The remaining GPRs hold either the beginning of variable-argument
3524 // data, or the beginning of an aggregate passed by value (usually
3525 // byval). Either way, we allocate stack slots adjacent to the data
3526 // provided by our caller, and store the unallocated registers there.
3527 // If this is a variadic function, the va_list pointer will begin with
3528 // these values; otherwise, this reassembles a (byval) structure that
3529 // was split between registers and memory.
3530 // Return: The frame index registers were stored into.
3531 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3532  const SDLoc &dl, SDValue &Chain,
3533  const Value *OrigArg,
3534  unsigned InRegsParamRecordIdx,
3535  int ArgOffset, unsigned ArgSize) const {
3536  // Currently, two use-cases possible:
3537  // Case #1. Non-var-args function, and we meet first byval parameter.
3538  // Setup first unallocated register as first byval register;
3539  // eat all remained registers
3540  // (these two actions are performed by HandleByVal method).
3541  // Then, here, we initialize stack frame with
3542  // "store-reg" instructions.
3543  // Case #2. Var-args function, that doesn't contain byval parameters.
3544  // The same: eat all remained unallocated registers,
3545  // initialize stack frame.
3546 
3547  MachineFunction &MF = DAG.getMachineFunction();
3548  MachineFrameInfo &MFI = MF.getFrameInfo();
3550  unsigned RBegin, REnd;
3551  if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3552  CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3553  } else {
3554  unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3555  RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3556  REnd = ARM::R4;
3557  }
3558 
3559  if (REnd != RBegin)
3560  ArgOffset = -4 * (ARM::R4 - RBegin);
3561 
3562  auto PtrVT = getPointerTy(DAG.getDataLayout());
3563  int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3564  SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3565 
3566  SmallVector<SDValue, 4> MemOps;
3567  const TargetRegisterClass *RC =
3568  AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3569 
3570  for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3571  unsigned VReg = MF.addLiveIn(Reg, RC);
3572  SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3573  SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3574  MachinePointerInfo(OrigArg, 4 * i));
3575  MemOps.push_back(Store);
3576  FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3577  }
3578 
3579  if (!MemOps.empty())
3580  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3581  return FrameIndex;
3582 }
3583 
3584 // Setup stack frame, the va_list pointer will start from.
3585 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3586  const SDLoc &dl, SDValue &Chain,
3587  unsigned ArgOffset,
3588  unsigned TotalArgRegsSaveSize,
3589  bool ForceMutable) const {
3590  MachineFunction &MF = DAG.getMachineFunction();
3592 
3593  // Try to store any remaining integer argument regs
3594  // to their spots on the stack so that they may be loaded by dereferencing
3595  // the result of va_next.
3596  // If there is no regs to be stored, just point address after last
3597  // argument passed via stack.
3598  int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3599  CCInfo.getInRegsParamsCount(),
3600  CCInfo.getNextStackOffset(), 4);
3601  AFI->setVarArgsFrameIndex(FrameIndex);
3602 }
3603 
3604 SDValue ARMTargetLowering::LowerFormalArguments(
3605  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3606  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3607  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3608  MachineFunction &MF = DAG.getMachineFunction();
3609  MachineFrameInfo &MFI = MF.getFrameInfo();
3610 
3612 
3613  // Assign locations to all of the incoming arguments.
3615  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3616  *DAG.getContext());
3617  CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3618 
3619  SmallVector<SDValue, 16> ArgValues;
3620  SDValue ArgValue;
3622  unsigned CurArgIdx = 0;
3623 
3624  // Initially ArgRegsSaveSize is zero.
3625  // Then we increase this value each time we meet byval parameter.
3626  // We also increase this value in case of varargs function.
3627  AFI->setArgRegsSaveSize(0);
3628 
3629  // Calculate the amount of stack space that we need to allocate to store
3630  // byval and variadic arguments that are passed in registers.
3631  // We need to know this before we allocate the first byval or variadic
3632  // argument, as they will be allocated a stack slot below the CFA (Canonical
3633  // Frame Address, the stack pointer at entry to the function).
3634  unsigned ArgRegBegin = ARM::R4;
3635  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3636  if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3637  break;
3638 
3639  CCValAssign &VA = ArgLocs[i];
3640  unsigned Index = VA.getValNo();
3641  ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3642  if (!Flags.isByVal())
3643  continue;
3644 
3645  assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3646  unsigned RBegin, REnd;
3647  CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3648  ArgRegBegin = std::min(ArgRegBegin, RBegin);
3649 
3650  CCInfo.nextInRegsParam();
3651  }
3652  CCInfo.rewindByValRegsInfo();
3653 
3654  int lastInsIndex = -1;
3655  if (isVarArg && MFI.hasVAStart()) {
3656  unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3657  if (RegIdx != array_lengthof(GPRArgRegs))
3658  ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3659  }
3660 
3661  unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3662  AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3663  auto PtrVT = getPointerTy(DAG.getDataLayout());
3664 
3665  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3666  CCValAssign &VA = ArgLocs[i];
3667  if (Ins[VA.getValNo()].isOrigArg()) {
3668  std::advance(CurOrigArg,
3669  Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3670  CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3671  }
3672  // Arguments stored in registers.
3673  if (VA.isRegLoc()) {
3674  EVT RegVT = VA.getLocVT();
3675 
3676  if (VA.needsCustom()) {
3677  // f64 and vector types are split up into multiple registers or
3678  // combinations of registers and stack slots.
3679  if (VA.getLocVT() == MVT::v2f64) {
3680  SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3681  Chain, DAG, dl);
3682  VA = ArgLocs[++i]; // skip ahead to next loc
3683  SDValue ArgValue2;
3684  if (VA.isMemLoc()) {
3685  int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3686  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3687  ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3689  DAG.getMachineFunction(), FI));
3690  } else {
3691  ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3692  Chain, DAG, dl);
3693  }
3694  ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3695  ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3696  ArgValue, ArgValue1,
3697  DAG.getIntPtrConstant(0, dl));
3698  ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3699  ArgValue, ArgValue2,
3700  DAG.getIntPtrConstant(1, dl));
3701  } else
3702  ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3703  } else {
3704  const TargetRegisterClass *RC;
3705 
3706 
3707  if (RegVT == MVT::f16)
3708  RC = &ARM::HPRRegClass;
3709  else if (RegVT == MVT::f32)
3710  RC = &ARM::SPRRegClass;
3711  else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
3712  RC = &ARM::DPRRegClass;
3713  else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
3714  RC = &ARM::QPRRegClass;
3715  else if (RegVT == MVT::i32)
3716  RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3717  : &ARM::GPRRegClass;
3718  else
3719  llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3720 
3721  // Transform the arguments in physical registers into virtual ones.
3722  unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3723  ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3724  }
3725 
3726  // If this is an 8 or 16-bit value, it is really passed promoted
3727  // to 32 bits. Insert an assert[sz]ext to capture this, then
3728  // truncate to the right size.
3729  switch (VA.getLocInfo()) {
3730  default: llvm_unreachable("Unknown loc info!");
3731  case CCValAssign::Full: break;
3732  case CCValAssign::BCvt:
3733  ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3734  break;
3735  case CCValAssign::SExt:
3736  ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3737  DAG.getValueType(VA.getValVT()));
3738  ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3739  break;
3740  case CCValAssign::ZExt:
3741  ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3742  DAG.getValueType(VA.getValVT()));
3743  ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3744  break;
3745  }
3746 
3747  InVals.push_back(ArgValue);
3748  } else { // VA.isRegLoc()
3749  // sanity check
3750  assert(VA.isMemLoc());
3751  assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3752 
3753  int index = VA.getValNo();
3754 
3755  // Some Ins[] entries become multiple ArgLoc[] entries.
3756  // Process them only once.
3757  if (index != lastInsIndex)
3758  {
3759  ISD::ArgFlagsTy Flags = Ins[index].Flags;
3760  // FIXME: For now, all byval parameter objects are marked mutable.
3761  // This can be changed with more analysis.
3762  // In case of tail call optimization mark all arguments mutable.
3763  // Since they could be overwritten by lowering of arguments in case of
3764  // a tail call.
3765  if (Flags.isByVal()) {
3766  assert(Ins[index].isOrigArg() &&
3767  "Byval arguments cannot be implicit");
3768  unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3769 
3770  int FrameIndex = StoreByValRegs(
3771  CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3772  VA.getLocMemOffset(), Flags.getByValSize());
3773  InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3774  CCInfo.nextInRegsParam();
3775  } else {
3776  unsigned FIOffset = VA.getLocMemOffset();
3777  int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3778  FIOffset, true);
3779 
3780  // Create load nodes to retrieve arguments from the stack.
3781  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3782  InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3784  DAG.getMachineFunction(), FI)));
3785  }
3786  lastInsIndex = index;
3787  }
3788  }
3789  }
3790 
3791  // varargs
3792  if (isVarArg && MFI.hasVAStart())
3793  VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3794  CCInfo.getNextStackOffset(),
3795  TotalArgRegsSaveSize);
3796 
3798 
3799  return Chain;
3800 }
3801 
3802 /// isFloatingPointZero - Return true if this is +0.0.
3803 static bool isFloatingPointZero(SDValue Op) {
3804  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3805  return CFP->getValueAPF().isPosZero();
3806  else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3807  // Maybe this has already been legalized into the constant pool?
3808  if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3809  SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3810  if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3811  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3812  return CFP->getValueAPF().isPosZero();
3813  }
3814  } else if (Op->getOpcode() == ISD::BITCAST &&
3815  Op->getValueType(0) == MVT::f64) {
3816  // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3817  // created by LowerConstantFP().
3818  SDValue BitcastOp = Op->getOperand(0);
3819  if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3820  isNullConstant(BitcastOp->getOperand(0)))
3821  return true;
3822  }
3823  return false;
3824 }
3825 
3826 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3827 /// the given operands.
3828 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3829  SDValue &ARMcc, SelectionDAG &DAG,
3830  const SDLoc &dl) const {
3831  if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3832  unsigned C = RHSC->getZExtValue();
3833  if (!isLegalICmpImmediate((int32_t)C)) {
3834  // Constant does not fit, try adjusting it by one.
3835  switch (CC) {
3836  default: break;
3837  case ISD::SETLT:
3838  case ISD::SETGE:
3839  if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3840  CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3841  RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3842  }
3843  break;
3844  case ISD::SETULT:
3845  case ISD::SETUGE:
3846  if (C != 0 && isLegalICmpImmediate(C-1)) {
3847  CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3848  RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3849  }
3850  break;
3851  case ISD::SETLE:
3852  case ISD::SETGT:
3853  if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3854  CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3855  RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3856  }
3857  break;
3858  case ISD::SETULE:
3859  case ISD::SETUGT:
3860  if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3861  CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3862  RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3863  }
3864  break;
3865  }
3866  }
3867  } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
3869  // In ARM and Thumb-2, the compare instructions can shift their second
3870  // operand.
3872  std::swap(LHS, RHS);
3873  }
3874 
3876  ARMISD::NodeType CompareType;
3877  switch (CondCode) {
3878  default:
3879  CompareType = ARMISD::CMP;
3880  break;
3881  case ARMCC::EQ:
3882  case ARMCC::NE:
3883  // Uses only Z Flag
3884  CompareType = ARMISD::CMPZ;
3885  break;
3886  }
3887  ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3888  return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3889 }
3890 
3891 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3892 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3893  SelectionDAG &DAG, const SDLoc &dl,
3894  bool InvalidOnQNaN) const {
3895  assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3896  SDValue Cmp;
3897  SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
3898  if (!isFloatingPointZero(RHS))
3899  Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
3900  else
3901  Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
3902  return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3903 }
3904 
3905 /// duplicateCmp - Glue values can have only one use, so this function
3906 /// duplicates a comparison node.
3907 SDValue
3908 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3909  unsigned Opc = Cmp.getOpcode();
3910  SDLoc DL(Cmp);
3911  if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3912  return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3913 
3914  assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3915  Cmp = Cmp.getOperand(0);
3916  Opc = Cmp.getOpcode();
3917  if (Opc == ARMISD::CMPFP)
3918  Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3919  Cmp.getOperand(1), Cmp.getOperand(2));
3920  else {
3921  assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3922  Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3923  Cmp.getOperand(1));
3924  }
3925  return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3926 }
3927 
3928 // This function returns three things: the arithmetic computation itself
3929 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc). The
3930 // comparison and the condition code define the case in which the arithmetic
3931 // computation *does not* overflow.
3932 std::pair<SDValue, SDValue>
3933 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3934  SDValue &ARMcc) const {
3935  assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3936 
3937  SDValue Value, OverflowCmp;
3938  SDValue LHS = Op.getOperand(0);
3939  SDValue RHS = Op.getOperand(1);
3940  SDLoc dl(Op);
3941 
3942  // FIXME: We are currently always generating CMPs because we don't support
3943  // generating CMN through the backend. This is not as good as the natural
3944  // CMP case because it causes a register dependency and cannot be folded
3945  // later.
3946 
3947  switch (Op.getOpcode()) {
3948  default:
3949  llvm_unreachable("Unknown overflow instruction!");
3950  case ISD::SADDO:
3951  ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3952  Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3953  OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3954  break;
3955  case ISD::UADDO:
3956  ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3957  // We use ADDC here to correspond to its use in LowerUnsignedALUO.
3958  // We do not use it in the USUBO case as Value may not be used.
3959  Value = DAG.getNode(ARMISD::ADDC, dl,
3960  DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
3961  .getValue(0);
3962  OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3963  break;
3964  case ISD::SSUBO:
3965  ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3966  Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3967  OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3968  break;
3969  case ISD::USUBO:
3970  ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3971  Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3972  OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3973  break;
3974  case ISD::UMULO:
3975  // We generate a UMUL_LOHI and then check if the high word is 0.
3976  ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
3977  Value = DAG.getNode(ISD::UMUL_LOHI, dl,
3978  DAG.getVTList(Op.getValueType(), Op.getValueType()),
3979  LHS, RHS);
3980  OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
3981  DAG.getConstant(0, dl, MVT::i32));
3982  Value = Value.getValue(0); // We only want the low 32 bits for the result.
3983  break;
3984  case ISD::SMULO:
3985  // We generate a SMUL_LOHI and then check if all the bits of the high word
3986  // are the same as the sign bit of the low word.
3987  ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
3988  Value = DAG.getNode(ISD::SMUL_LOHI, dl,
3989  DAG.getVTList(Op.getValueType(), Op.getValueType()),
3990  LHS, RHS);
3991  OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
3992  DAG.getNode(ISD::SRA, dl, Op.getValueType(),
3993  Value.getValue(0),
3994  DAG.getConstant(31, dl, MVT::i32)));
3995  Value = Value.getValue(0); // We only want the low 32 bits for the result.
3996  break;
3997  } // switch (...)
3998 
3999  return std::make_pair(Value, OverflowCmp);
4000 }
4001 
4002 SDValue
4003 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4004  // Let legalize expand this if it isn't a legal type yet.
4006  return SDValue();
4007 
4008  SDValue Value, OverflowCmp;
4009  SDValue ARMcc;
4010  std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4011  SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4012  SDLoc dl(Op);
4013  // We use 0 and 1 as false and true values.
4014  SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4015  SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4016  EVT VT = Op.getValueType();
4017 
4018  SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4019  ARMcc, CCR, OverflowCmp);
4020 
4021  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4022  return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4023 }
4024 
4026  SelectionDAG &DAG) {
4027  SDLoc DL(BoolCarry);
4028  EVT CarryVT = BoolCarry.getValueType();
4029 
4030  // This converts the boolean value carry into the carry flag by doing
4031  // ARMISD::SUBC Carry, 1
4032  SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4033  DAG.getVTList(CarryVT, MVT::i32),
4034  BoolCarry, DAG.getConstant(1, DL, CarryVT));
4035  return Carry.getValue(1);
4036 }
4037 
4039  SelectionDAG &DAG) {
4040  SDLoc DL(Flags);
4041 
4042  // Now convert the carry flag into a boolean carry. We do this
4043  // using ARMISD:ADDE 0, 0, Carry
4044  return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4045  DAG.getConstant(0, DL, MVT::i32),
4046  DAG.getConstant(0, DL, MVT::i32), Flags);
4047 }
4048 
4049 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4050  SelectionDAG &DAG) const {
4051  // Let legalize expand this if it isn't a legal type yet.
4053  return SDValue();
4054 
4055  SDValue LHS = Op.getOperand(0);
4056  SDValue RHS = Op.getOperand(1);
4057  SDLoc dl(Op);
4058 
4059  EVT VT = Op.getValueType();
4060  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4061  SDValue Value;
4062  SDValue Overflow;
4063  switch (Op.getOpcode()) {
4064  default: