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