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