LCOV - code coverage report
Current view: top level - lib/Target/AArch64 - AArch64ISelLowering.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 5151 5547 92.9 %
Date: 2017-09-14 15:23:50 Functions: 244 249 98.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation  ----===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This file implements the AArch64TargetLowering class.
      11             : //
      12             : //===----------------------------------------------------------------------===//
      13             : 
      14             : #include "AArch64ISelLowering.h"
      15             : #include "AArch64CallingConvention.h"
      16             : #include "AArch64MachineFunctionInfo.h"
      17             : #include "AArch64PerfectShuffle.h"
      18             : #include "AArch64RegisterInfo.h"
      19             : #include "AArch64Subtarget.h"
      20             : #include "MCTargetDesc/AArch64AddressingModes.h"
      21             : #include "Utils/AArch64BaseInfo.h"
      22             : #include "llvm/ADT/APFloat.h"
      23             : #include "llvm/ADT/APInt.h"
      24             : #include "llvm/ADT/ArrayRef.h"
      25             : #include "llvm/ADT/STLExtras.h"
      26             : #include "llvm/ADT/SmallVector.h"
      27             : #include "llvm/ADT/Statistic.h"
      28             : #include "llvm/ADT/StringRef.h"
      29             : #include "llvm/ADT/StringSwitch.h"
      30             : #include "llvm/ADT/Triple.h"
      31             : #include "llvm/ADT/Twine.h"
      32             : #include "llvm/Analysis/VectorUtils.h"
      33             : #include "llvm/CodeGen/CallingConvLower.h"
      34             : #include "llvm/CodeGen/MachineBasicBlock.h"
      35             : #include "llvm/CodeGen/MachineFrameInfo.h"
      36             : #include "llvm/CodeGen/MachineFunction.h"
      37             : #include "llvm/CodeGen/MachineInstr.h"
      38             : #include "llvm/CodeGen/MachineInstrBuilder.h"
      39             : #include "llvm/CodeGen/MachineMemOperand.h"
      40             : #include "llvm/CodeGen/MachineRegisterInfo.h"
      41             : #include "llvm/CodeGen/MachineValueType.h"
      42             : #include "llvm/CodeGen/RuntimeLibcalls.h"
      43             : #include "llvm/CodeGen/SelectionDAG.h"
      44             : #include "llvm/CodeGen/SelectionDAGNodes.h"
      45             : #include "llvm/CodeGen/ValueTypes.h"
      46             : #include "llvm/IR/Attributes.h"
      47             : #include "llvm/IR/Constants.h"
      48             : #include "llvm/IR/DataLayout.h"
      49             : #include "llvm/IR/DebugLoc.h"
      50             : #include "llvm/IR/DerivedTypes.h"
      51             : #include "llvm/IR/Function.h"
      52             : #include "llvm/IR/GetElementPtrTypeIterator.h"
      53             : #include "llvm/IR/GlobalValue.h"
      54             : #include "llvm/IR/IRBuilder.h"
      55             : #include "llvm/IR/Instruction.h"
      56             : #include "llvm/IR/Instructions.h"
      57             : #include "llvm/IR/Intrinsics.h"
      58             : #include "llvm/IR/Module.h"
      59             : #include "llvm/IR/OperandTraits.h"
      60             : #include "llvm/IR/Type.h"
      61             : #include "llvm/IR/Use.h"
      62             : #include "llvm/IR/Value.h"
      63             : #include "llvm/MC/MCRegisterInfo.h"
      64             : #include "llvm/Support/Casting.h"
      65             : #include "llvm/Support/CodeGen.h"
      66             : #include "llvm/Support/CommandLine.h"
      67             : #include "llvm/Support/Compiler.h"
      68             : #include "llvm/Support/Debug.h"
      69             : #include "llvm/Support/ErrorHandling.h"
      70             : #include "llvm/Support/KnownBits.h"
      71             : #include "llvm/Support/MathExtras.h"
      72             : #include "llvm/Support/raw_ostream.h"
      73             : #include "llvm/Target/TargetCallingConv.h"
      74             : #include "llvm/Target/TargetInstrInfo.h"
      75             : #include "llvm/Target/TargetMachine.h"
      76             : #include "llvm/Target/TargetOptions.h"
      77             : #include <algorithm>
      78             : #include <bitset>
      79             : #include <cassert>
      80             : #include <cctype>
      81             : #include <cstdint>
      82             : #include <cstdlib>
      83             : #include <iterator>
      84             : #include <limits>
      85             : #include <tuple>
      86             : #include <utility>
      87             : #include <vector>
      88             : 
      89             : using namespace llvm;
      90             : 
      91             : #define DEBUG_TYPE "aarch64-lower"
      92             : 
      93             : STATISTIC(NumTailCalls, "Number of tail calls");
      94             : STATISTIC(NumShiftInserts, "Number of vector shift inserts");
      95             : STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
      96             : 
      97             : static cl::opt<bool>
      98       72306 : EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
      99      216918 :                            cl::desc("Allow AArch64 SLI/SRI formation"),
     100      289224 :                            cl::init(false));
     101             : 
     102             : // FIXME: The necessary dtprel relocations don't seem to be supported
     103             : // well in the GNU bfd and gold linkers at the moment. Therefore, by
     104             : // default, for now, fall back to GeneralDynamic code generation.
     105       72306 : cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
     106             :     "aarch64-elf-ldtls-generation", cl::Hidden,
     107      216918 :     cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
     108      289224 :     cl::init(false));
     109             : 
     110             : static cl::opt<bool>
     111       72306 : EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
     112      216918 :                          cl::desc("Enable AArch64 logical imm instruction "
     113             :                                   "optimization"),
     114      289224 :                          cl::init(true));
     115             : 
     116             : /// Value type used for condition codes.
     117             : static const MVT MVT_CC = MVT::i32;
     118             : 
     119        1214 : AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
     120        1214 :                                              const AArch64Subtarget &STI)
     121        1214 :     : TargetLowering(TM), Subtarget(&STI) {
     122             :   // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
     123             :   // we have to make something up. Arbitrarily, choose ZeroOrOne.
     124        2428 :   setBooleanContents(ZeroOrOneBooleanContent);
     125             :   // When comparing vectors the result sets the different elements in the
     126             :   // vector to all-one or all-zero.
     127        2428 :   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
     128             : 
     129             :   // Set up the register classes.
     130        2428 :   addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
     131        2428 :   addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
     132             : 
     133        1214 :   if (Subtarget->hasFPARMv8()) {
     134        2400 :     addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
     135        2400 :     addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
     136        2400 :     addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
     137        2400 :     addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
     138             :   }
     139             : 
     140        1214 :   if (Subtarget->hasNEON()) {
     141        2388 :     addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
     142        2388 :     addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
     143             :     // Someone set us up the NEON.
     144        1194 :     addDRTypeForNEON(MVT::v2f32);
     145        1194 :     addDRTypeForNEON(MVT::v8i8);
     146        1194 :     addDRTypeForNEON(MVT::v4i16);
     147        1194 :     addDRTypeForNEON(MVT::v2i32);
     148        1194 :     addDRTypeForNEON(MVT::v1i64);
     149        1194 :     addDRTypeForNEON(MVT::v1f64);
     150        1194 :     addDRTypeForNEON(MVT::v4f16);
     151             : 
     152        1194 :     addQRTypeForNEON(MVT::v4f32);
     153        1194 :     addQRTypeForNEON(MVT::v2f64);
     154        1194 :     addQRTypeForNEON(MVT::v16i8);
     155        1194 :     addQRTypeForNEON(MVT::v8i16);
     156        1194 :     addQRTypeForNEON(MVT::v4i32);
     157        1194 :     addQRTypeForNEON(MVT::v2i64);
     158        1194 :     addQRTypeForNEON(MVT::v8f16);
     159             :   }
     160             : 
     161             :   // Compute derived properties from the register classes
     162        2428 :   computeRegisterProperties(Subtarget->getRegisterInfo());
     163             : 
     164             :   // Provide all sorts of operation actions
     165        2428 :   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
     166        2428 :   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
     167        2428 :   setOperationAction(ISD::SETCC, MVT::i32, Custom);
     168        2428 :   setOperationAction(ISD::SETCC, MVT::i64, Custom);
     169        2428 :   setOperationAction(ISD::SETCC, MVT::f16, Custom);
     170        2428 :   setOperationAction(ISD::SETCC, MVT::f32, Custom);
     171        2428 :   setOperationAction(ISD::SETCC, MVT::f64, Custom);
     172        2428 :   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
     173        2428 :   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
     174        2428 :   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
     175        2428 :   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
     176        2428 :   setOperationAction(ISD::BR_CC, MVT::i64, Custom);
     177        2428 :   setOperationAction(ISD::BR_CC, MVT::f16, Custom);
     178        2428 :   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
     179        2428 :   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
     180        2428 :   setOperationAction(ISD::SELECT, MVT::i32, Custom);
     181        2428 :   setOperationAction(ISD::SELECT, MVT::i64, Custom);
     182        2428 :   setOperationAction(ISD::SELECT, MVT::f16, Custom);
     183        2428 :   setOperationAction(ISD::SELECT, MVT::f32, Custom);
     184        2428 :   setOperationAction(ISD::SELECT, MVT::f64, Custom);
     185        2428 :   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
     186        2428 :   setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
     187        2428 :   setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
     188        2428 :   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
     189        2428 :   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
     190        2428 :   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
     191        2428 :   setOperationAction(ISD::JumpTable, MVT::i64, Custom);
     192             : 
     193        2428 :   setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
     194        2428 :   setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
     195        2428 :   setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
     196             : 
     197        2428 :   setOperationAction(ISD::FREM, MVT::f32, Expand);
     198        2428 :   setOperationAction(ISD::FREM, MVT::f64, Expand);
     199        2428 :   setOperationAction(ISD::FREM, MVT::f80, Expand);
     200             : 
     201             :   // Custom lowering hooks are needed for XOR
     202             :   // to fold it into CSINC/CSINV.
     203        2428 :   setOperationAction(ISD::XOR, MVT::i32, Custom);
     204        2428 :   setOperationAction(ISD::XOR, MVT::i64, Custom);
     205             : 
     206             :   // Virtually no operation on f128 is legal, but LLVM can't expand them when
     207             :   // there's a valid register class, so we need custom operations in most cases.
     208        2428 :   setOperationAction(ISD::FABS, MVT::f128, Expand);
     209        2428 :   setOperationAction(ISD::FADD, MVT::f128, Custom);
     210        2428 :   setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
     211        2428 :   setOperationAction(ISD::FCOS, MVT::f128, Expand);
     212        2428 :   setOperationAction(ISD::FDIV, MVT::f128, Custom);
     213        2428 :   setOperationAction(ISD::FMA, MVT::f128, Expand);
     214        2428 :   setOperationAction(ISD::FMUL, MVT::f128, Custom);
     215        2428 :   setOperationAction(ISD::FNEG, MVT::f128, Expand);
     216        2428 :   setOperationAction(ISD::FPOW, MVT::f128, Expand);
     217        2428 :   setOperationAction(ISD::FREM, MVT::f128, Expand);
     218        2428 :   setOperationAction(ISD::FRINT, MVT::f128, Expand);
     219        2428 :   setOperationAction(ISD::FSIN, MVT::f128, Expand);
     220        2428 :   setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
     221        2428 :   setOperationAction(ISD::FSQRT, MVT::f128, Expand);
     222        2428 :   setOperationAction(ISD::FSUB, MVT::f128, Custom);
     223        2428 :   setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
     224        2428 :   setOperationAction(ISD::SETCC, MVT::f128, Custom);
     225        2428 :   setOperationAction(ISD::BR_CC, MVT::f128, Custom);
     226        2428 :   setOperationAction(ISD::SELECT, MVT::f128, Custom);
     227        2428 :   setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
     228        2428 :   setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
     229             : 
     230             :   // Lowering for many of the conversions is actually specified by the non-f128
     231             :   // type. The LowerXXX function will be trivial when f128 isn't involved.
     232        2428 :   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
     233        2428 :   setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
     234        2428 :   setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
     235        2428 :   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
     236        2428 :   setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
     237        2428 :   setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
     238        2428 :   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
     239        2428 :   setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
     240        2428 :   setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
     241        2428 :   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
     242        2428 :   setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
     243        2428 :   setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
     244        2428 :   setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
     245        2428 :   setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
     246             : 
     247             :   // Variable arguments.
     248        2428 :   setOperationAction(ISD::VASTART, MVT::Other, Custom);
     249        2428 :   setOperationAction(ISD::VAARG, MVT::Other, Custom);
     250        2428 :   setOperationAction(ISD::VACOPY, MVT::Other, Custom);
     251        2428 :   setOperationAction(ISD::VAEND, MVT::Other, Expand);
     252             : 
     253             :   // Variable-sized objects.
     254        2428 :   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
     255        2428 :   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
     256        2428 :   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
     257             : 
     258             :   // Constant pool entries
     259        2428 :   setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
     260             : 
     261             :   // BlockAddress
     262        2428 :   setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
     263             : 
     264             :   // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
     265        2428 :   setOperationAction(ISD::ADDC, MVT::i32, Custom);
     266        2428 :   setOperationAction(ISD::ADDE, MVT::i32, Custom);
     267        2428 :   setOperationAction(ISD::SUBC, MVT::i32, Custom);
     268        2428 :   setOperationAction(ISD::SUBE, MVT::i32, Custom);
     269        2428 :   setOperationAction(ISD::ADDC, MVT::i64, Custom);
     270        2428 :   setOperationAction(ISD::ADDE, MVT::i64, Custom);
     271        2428 :   setOperationAction(ISD::SUBC, MVT::i64, Custom);
     272        2428 :   setOperationAction(ISD::SUBE, MVT::i64, Custom);
     273             : 
     274             :   // AArch64 lacks both left-rotate and popcount instructions.
     275        2428 :   setOperationAction(ISD::ROTL, MVT::i32, Expand);
     276        2428 :   setOperationAction(ISD::ROTL, MVT::i64, Expand);
     277      115330 :   for (MVT VT : MVT::vector_valuetypes()) {
     278      228232 :     setOperationAction(ISD::ROTL, VT, Expand);
     279      228232 :     setOperationAction(ISD::ROTR, VT, Expand);
     280             :   }
     281             : 
     282             :   // AArch64 doesn't have {U|S}MUL_LOHI.
     283        2428 :   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
     284        2428 :   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
     285             : 
     286        2428 :   setOperationAction(ISD::CTPOP, MVT::i32, Custom);
     287        2428 :   setOperationAction(ISD::CTPOP, MVT::i64, Custom);
     288             : 
     289        2428 :   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
     290        2428 :   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
     291      115330 :   for (MVT VT : MVT::vector_valuetypes()) {
     292      228232 :     setOperationAction(ISD::SDIVREM, VT, Expand);
     293      228232 :     setOperationAction(ISD::UDIVREM, VT, Expand);
     294             :   }
     295        2428 :   setOperationAction(ISD::SREM, MVT::i32, Expand);
     296        2428 :   setOperationAction(ISD::SREM, MVT::i64, Expand);
     297        2428 :   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
     298        2428 :   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
     299        2428 :   setOperationAction(ISD::UREM, MVT::i32, Expand);
     300        2428 :   setOperationAction(ISD::UREM, MVT::i64, Expand);
     301             : 
     302             :   // Custom lower Add/Sub/Mul with overflow.
     303        2428 :   setOperationAction(ISD::SADDO, MVT::i32, Custom);
     304        2428 :   setOperationAction(ISD::SADDO, MVT::i64, Custom);
     305        2428 :   setOperationAction(ISD::UADDO, MVT::i32, Custom);
     306        2428 :   setOperationAction(ISD::UADDO, MVT::i64, Custom);
     307        2428 :   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
     308        2428 :   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
     309        2428 :   setOperationAction(ISD::USUBO, MVT::i32, Custom);
     310        2428 :   setOperationAction(ISD::USUBO, MVT::i64, Custom);
     311        2428 :   setOperationAction(ISD::SMULO, MVT::i32, Custom);
     312        2428 :   setOperationAction(ISD::SMULO, MVT::i64, Custom);
     313        2428 :   setOperationAction(ISD::UMULO, MVT::i32, Custom);
     314        2428 :   setOperationAction(ISD::UMULO, MVT::i64, Custom);
     315             : 
     316        2428 :   setOperationAction(ISD::FSIN, MVT::f32, Expand);
     317        2428 :   setOperationAction(ISD::FSIN, MVT::f64, Expand);
     318        2428 :   setOperationAction(ISD::FCOS, MVT::f32, Expand);
     319        2428 :   setOperationAction(ISD::FCOS, MVT::f64, Expand);
     320        2428 :   setOperationAction(ISD::FPOW, MVT::f32, Expand);
     321        2428 :   setOperationAction(ISD::FPOW, MVT::f64, Expand);
     322        2428 :   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
     323        2428 :   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
     324        1214 :   if (Subtarget->hasFullFP16())
     325          20 :     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
     326             :   else
     327        2408 :     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
     328             : 
     329        2428 :   setOperationAction(ISD::FREM,    MVT::f16,   Promote);
     330        2428 :   setOperationAction(ISD::FREM,    MVT::v4f16, Promote);
     331        2428 :   setOperationAction(ISD::FPOW,    MVT::f16,   Promote);
     332        2428 :   setOperationAction(ISD::FPOW,    MVT::v4f16, Promote);
     333        2428 :   setOperationAction(ISD::FPOWI,   MVT::f16,   Promote);
     334        2428 :   setOperationAction(ISD::FCOS,    MVT::f16,   Promote);
     335        2428 :   setOperationAction(ISD::FCOS,    MVT::v4f16, Promote);
     336        2428 :   setOperationAction(ISD::FSIN,    MVT::f16,   Promote);
     337        2428 :   setOperationAction(ISD::FSIN,    MVT::v4f16, Promote);
     338        2428 :   setOperationAction(ISD::FSINCOS, MVT::f16,   Promote);
     339        2428 :   setOperationAction(ISD::FSINCOS, MVT::v4f16, Promote);
     340        2428 :   setOperationAction(ISD::FEXP,    MVT::f16,   Promote);
     341        2428 :   setOperationAction(ISD::FEXP,    MVT::v4f16, Promote);
     342        2428 :   setOperationAction(ISD::FEXP2,   MVT::f16,   Promote);
     343        2428 :   setOperationAction(ISD::FEXP2,   MVT::v4f16, Promote);
     344        2428 :   setOperationAction(ISD::FLOG,    MVT::f16,   Promote);
     345        2428 :   setOperationAction(ISD::FLOG,    MVT::v4f16, Promote);
     346        2428 :   setOperationAction(ISD::FLOG2,   MVT::f16,   Promote);
     347        2428 :   setOperationAction(ISD::FLOG2,   MVT::v4f16, Promote);
     348        2428 :   setOperationAction(ISD::FLOG10,  MVT::f16,   Promote);
     349        2428 :   setOperationAction(ISD::FLOG10,  MVT::v4f16, Promote);
     350             : 
     351        1214 :   if (!Subtarget->hasFullFP16()) {
     352        2408 :     setOperationAction(ISD::SELECT,      MVT::f16,  Promote);
     353        2408 :     setOperationAction(ISD::SELECT_CC,   MVT::f16,  Promote);
     354        2408 :     setOperationAction(ISD::SETCC,       MVT::f16,  Promote);
     355        2408 :     setOperationAction(ISD::BR_CC,       MVT::f16,  Promote);
     356        2408 :     setOperationAction(ISD::FADD,        MVT::f16,  Promote);
     357        2408 :     setOperationAction(ISD::FSUB,        MVT::f16,  Promote);
     358        2408 :     setOperationAction(ISD::FMUL,        MVT::f16,  Promote);
     359        2408 :     setOperationAction(ISD::FDIV,        MVT::f16,  Promote);
     360        2408 :     setOperationAction(ISD::FMA,         MVT::f16,  Promote);
     361        2408 :     setOperationAction(ISD::FNEG,        MVT::f16,  Promote);
     362        2408 :     setOperationAction(ISD::FABS,        MVT::f16,  Promote);
     363        2408 :     setOperationAction(ISD::FCEIL,       MVT::f16,  Promote);
     364        2408 :     setOperationAction(ISD::FSQRT,       MVT::f16,  Promote);
     365        2408 :     setOperationAction(ISD::FFLOOR,      MVT::f16,  Promote);
     366        2408 :     setOperationAction(ISD::FNEARBYINT,  MVT::f16,  Promote);
     367        2408 :     setOperationAction(ISD::FRINT,       MVT::f16,  Promote);
     368        2408 :     setOperationAction(ISD::FROUND,      MVT::f16,  Promote);
     369        2408 :     setOperationAction(ISD::FTRUNC,      MVT::f16,  Promote);
     370        2408 :     setOperationAction(ISD::FMINNUM,     MVT::f16,  Promote);
     371        2408 :     setOperationAction(ISD::FMAXNUM,     MVT::f16,  Promote);
     372        2408 :     setOperationAction(ISD::FMINNAN,     MVT::f16,  Promote);
     373        2408 :     setOperationAction(ISD::FMAXNAN,     MVT::f16,  Promote);
     374             : 
     375             :     // promote v4f16 to v4f32 when that is known to be safe.
     376        2408 :     setOperationAction(ISD::FADD,        MVT::v4f16, Promote);
     377        2408 :     setOperationAction(ISD::FSUB,        MVT::v4f16, Promote);
     378        2408 :     setOperationAction(ISD::FMUL,        MVT::v4f16, Promote);
     379        2408 :     setOperationAction(ISD::FDIV,        MVT::v4f16, Promote);
     380        2408 :     setOperationAction(ISD::FP_EXTEND,   MVT::v4f16, Promote);
     381        2408 :     setOperationAction(ISD::FP_ROUND,    MVT::v4f16, Promote);
     382        2408 :     AddPromotedToType(ISD::FADD,         MVT::v4f16, MVT::v4f32);
     383        2408 :     AddPromotedToType(ISD::FSUB,         MVT::v4f16, MVT::v4f32);
     384        2408 :     AddPromotedToType(ISD::FMUL,         MVT::v4f16, MVT::v4f32);
     385        2408 :     AddPromotedToType(ISD::FDIV,         MVT::v4f16, MVT::v4f32);
     386        2408 :     AddPromotedToType(ISD::FP_EXTEND,    MVT::v4f16, MVT::v4f32);
     387        2408 :     AddPromotedToType(ISD::FP_ROUND,     MVT::v4f16, MVT::v4f32);
     388             : 
     389        2408 :     setOperationAction(ISD::FABS,        MVT::v4f16, Expand);
     390        2408 :     setOperationAction(ISD::FNEG,        MVT::v4f16, Expand);
     391        2408 :     setOperationAction(ISD::FROUND,      MVT::v4f16, Expand);
     392        2408 :     setOperationAction(ISD::FMA,         MVT::v4f16, Expand);
     393        2408 :     setOperationAction(ISD::SETCC,       MVT::v4f16, Expand);
     394        2408 :     setOperationAction(ISD::BR_CC,       MVT::v4f16, Expand);
     395        2408 :     setOperationAction(ISD::SELECT,      MVT::v4f16, Expand);
     396        2408 :     setOperationAction(ISD::SELECT_CC,   MVT::v4f16, Expand);
     397        2408 :     setOperationAction(ISD::FTRUNC,      MVT::v4f16, Expand);
     398        2408 :     setOperationAction(ISD::FCOPYSIGN,   MVT::v4f16, Expand);
     399        2408 :     setOperationAction(ISD::FFLOOR,      MVT::v4f16, Expand);
     400        2408 :     setOperationAction(ISD::FCEIL,       MVT::v4f16, Expand);
     401        2408 :     setOperationAction(ISD::FRINT,       MVT::v4f16, Expand);
     402        2408 :     setOperationAction(ISD::FNEARBYINT,  MVT::v4f16, Expand);
     403        2408 :     setOperationAction(ISD::FSQRT,       MVT::v4f16, Expand);
     404             :   }
     405             : 
     406             :   
     407             :   // v8f16 is also a storage-only type, so expand it.
     408        2428 :   setOperationAction(ISD::FABS, MVT::v8f16, Expand);
     409        2428 :   setOperationAction(ISD::FADD, MVT::v8f16, Expand);
     410        2428 :   setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
     411        2428 :   setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
     412        2428 :   setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
     413        2428 :   setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
     414        2428 :   setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
     415        2428 :   setOperationAction(ISD::FMA, MVT::v8f16, Expand);
     416        2428 :   setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
     417        2428 :   setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
     418        2428 :   setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
     419        2428 :   setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
     420        2428 :   setOperationAction(ISD::FREM, MVT::v8f16, Expand);
     421        2428 :   setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
     422        2428 :   setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
     423        2428 :   setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
     424        2428 :   setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
     425        2428 :   setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
     426        2428 :   setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
     427        2428 :   setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
     428        2428 :   setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
     429        2428 :   setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
     430        2428 :   setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
     431        2428 :   setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
     432        2428 :   setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
     433        2428 :   setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
     434        2428 :   setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
     435        2428 :   setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
     436        2428 :   setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
     437        2428 :   setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
     438             : 
     439             :   // AArch64 has implementations of a lot of rounding-like FP operations.
     440        7284 :   for (MVT Ty : {MVT::f32, MVT::f64}) {
     441        4856 :     setOperationAction(ISD::FFLOOR, Ty, Legal);
     442        4856 :     setOperationAction(ISD::FNEARBYINT, Ty, Legal);
     443        4856 :     setOperationAction(ISD::FCEIL, Ty, Legal);
     444        4856 :     setOperationAction(ISD::FRINT, Ty, Legal);
     445        4856 :     setOperationAction(ISD::FTRUNC, Ty, Legal);
     446        4856 :     setOperationAction(ISD::FROUND, Ty, Legal);
     447        4856 :     setOperationAction(ISD::FMINNUM, Ty, Legal);
     448        4856 :     setOperationAction(ISD::FMAXNUM, Ty, Legal);
     449        4856 :     setOperationAction(ISD::FMINNAN, Ty, Legal);
     450        4856 :     setOperationAction(ISD::FMAXNAN, Ty, Legal);
     451             :   }
     452             : 
     453        1214 :   if (Subtarget->hasFullFP16()) {
     454          20 :     setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
     455          20 :     setOperationAction(ISD::FFLOOR,  MVT::f16, Legal);
     456          20 :     setOperationAction(ISD::FCEIL,   MVT::f16, Legal);
     457          20 :     setOperationAction(ISD::FRINT,   MVT::f16, Legal);
     458          20 :     setOperationAction(ISD::FTRUNC,  MVT::f16, Legal);
     459          20 :     setOperationAction(ISD::FROUND,  MVT::f16, Legal);
     460          20 :     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
     461          20 :     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
     462          20 :     setOperationAction(ISD::FMINNAN, MVT::f16, Legal);
     463          20 :     setOperationAction(ISD::FMAXNAN, MVT::f16, Legal);
     464             :   }
     465             : 
     466        2428 :   setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
     467             : 
     468        2428 :   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
     469             : 
     470             :   // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
     471             :   // This requires the Performance Monitors extension.
     472        1214 :   if (Subtarget->hasPerfMon())
     473        2414 :     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
     474             : 
     475        2428 :   if (Subtarget->isTargetMachO()) {
     476             :     // For iOS, we don't want to the normal expansion of a libcall to
     477             :     // sincos. We want to issue a libcall to __sincos_stret to avoid memory
     478             :     // traffic.
     479         680 :     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
     480         680 :     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
     481             :   } else {
     482        1748 :     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
     483        1748 :     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
     484             :   }
     485             : 
     486             :   // Make floating-point constants legal for the large code model, so they don't
     487             :   // become loads from the constant pool.
     488        2428 :   if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
     489           8 :     setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
     490           8 :     setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
     491             :   }
     492             : 
     493             :   // AArch64 does not have floating-point extending loads, i1 sign-extending
     494             :   // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
     495       15782 :   for (MVT VT : MVT::fp_valuetypes()) {
     496       14568 :     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
     497       14568 :     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
     498       14568 :     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
     499       14568 :     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
     500             :   }
     501       15782 :   for (MVT VT : MVT::integer_valuetypes())
     502       14568 :     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
     503             : 
     504        2428 :   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
     505        2428 :   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
     506        2428 :   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
     507        2428 :   setTruncStoreAction(MVT::f128, MVT::f80, Expand);
     508        2428 :   setTruncStoreAction(MVT::f128, MVT::f64, Expand);
     509        2428 :   setTruncStoreAction(MVT::f128, MVT::f32, Expand);
     510        2428 :   setTruncStoreAction(MVT::f128, MVT::f16, Expand);
     511             : 
     512        2428 :   setOperationAction(ISD::BITCAST, MVT::i16, Custom);
     513        2428 :   setOperationAction(ISD::BITCAST, MVT::f16, Custom);
     514             : 
     515             :   // Indexed loads and stores are supported.
     516        6070 :   for (unsigned im = (unsigned)ISD::PRE_INC;
     517        6070 :        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
     518        9712 :     setIndexedLoadAction(im, MVT::i8, Legal);
     519        9712 :     setIndexedLoadAction(im, MVT::i16, Legal);
     520        9712 :     setIndexedLoadAction(im, MVT::i32, Legal);
     521        9712 :     setIndexedLoadAction(im, MVT::i64, Legal);
     522        9712 :     setIndexedLoadAction(im, MVT::f64, Legal);
     523        9712 :     setIndexedLoadAction(im, MVT::f32, Legal);
     524        9712 :     setIndexedLoadAction(im, MVT::f16, Legal);
     525        9712 :     setIndexedStoreAction(im, MVT::i8, Legal);
     526        9712 :     setIndexedStoreAction(im, MVT::i16, Legal);
     527        9712 :     setIndexedStoreAction(im, MVT::i32, Legal);
     528        9712 :     setIndexedStoreAction(im, MVT::i64, Legal);
     529        9712 :     setIndexedStoreAction(im, MVT::f64, Legal);
     530        9712 :     setIndexedStoreAction(im, MVT::f32, Legal);
     531        9712 :     setIndexedStoreAction(im, MVT::f16, Legal);
     532             :   }
     533             : 
     534             :   // Trap.
     535        2428 :   setOperationAction(ISD::TRAP, MVT::Other, Legal);
     536             : 
     537             :   // We combine OR nodes for bitfield operations.
     538        2428 :   setTargetDAGCombine(ISD::OR);
     539             : 
     540             :   // Vector add and sub nodes may conceal a high-half opportunity.
     541             :   // Also, try to fold ADD into CSINC/CSINV..
     542        2428 :   setTargetDAGCombine(ISD::ADD);
     543        2428 :   setTargetDAGCombine(ISD::SUB);
     544        2428 :   setTargetDAGCombine(ISD::SRL);
     545        2428 :   setTargetDAGCombine(ISD::XOR);
     546        2428 :   setTargetDAGCombine(ISD::SINT_TO_FP);
     547        2428 :   setTargetDAGCombine(ISD::UINT_TO_FP);
     548             : 
     549        2428 :   setTargetDAGCombine(ISD::FP_TO_SINT);
     550        2428 :   setTargetDAGCombine(ISD::FP_TO_UINT);
     551        2428 :   setTargetDAGCombine(ISD::FDIV);
     552             : 
     553        2428 :   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
     554             : 
     555        2428 :   setTargetDAGCombine(ISD::ANY_EXTEND);
     556        2428 :   setTargetDAGCombine(ISD::ZERO_EXTEND);
     557        2428 :   setTargetDAGCombine(ISD::SIGN_EXTEND);
     558        2428 :   setTargetDAGCombine(ISD::BITCAST);
     559        2428 :   setTargetDAGCombine(ISD::CONCAT_VECTORS);
     560        2428 :   setTargetDAGCombine(ISD::STORE);
     561        1214 :   if (Subtarget->supportsAddressTopByteIgnored())
     562           1 :     setTargetDAGCombine(ISD::LOAD);
     563             : 
     564        2428 :   setTargetDAGCombine(ISD::MUL);
     565             : 
     566        2428 :   setTargetDAGCombine(ISD::SELECT);
     567        2428 :   setTargetDAGCombine(ISD::VSELECT);
     568             : 
     569        2428 :   setTargetDAGCombine(ISD::INTRINSIC_VOID);
     570        2428 :   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
     571        2428 :   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
     572             : 
     573        1214 :   MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
     574        1214 :   MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
     575        1214 :   MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
     576             : 
     577        2428 :   setStackPointerRegisterToSaveRestore(AArch64::SP);
     578             : 
     579        2428 :   setSchedulingPreference(Sched::Hybrid);
     580             : 
     581        1214 :   EnableExtLdPromotion = true;
     582             : 
     583             :   // Set required alignment.
     584        2428 :   setMinFunctionAlignment(2);
     585             :   // Set preferred alignments.
     586        2428 :   setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
     587        2428 :   setPrefLoopAlignment(STI.getPrefLoopAlignment());
     588             : 
     589             :   // Only change the limit for entries in a jump table if specified by
     590             :   // the subtarget, but not at the command line.
     591        1214 :   unsigned MaxJT = STI.getMaximumJumpTableSize();
     592        1214 :   if (MaxJT && getMaximumJumpTableSize() == 0)
     593          16 :     setMaximumJumpTableSize(MaxJT);
     594             : 
     595        2428 :   setHasExtractBitsInsn(true);
     596             : 
     597        2428 :   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
     598             : 
     599        1214 :   if (Subtarget->hasNEON()) {
     600             :     // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
     601             :     // silliness like this:
     602        2388 :     setOperationAction(ISD::FABS, MVT::v1f64, Expand);
     603        2388 :     setOperationAction(ISD::FADD, MVT::v1f64, Expand);
     604        2388 :     setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
     605        2388 :     setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
     606        2388 :     setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
     607        2388 :     setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
     608        2388 :     setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
     609        2388 :     setOperationAction(ISD::FMA, MVT::v1f64, Expand);
     610        2388 :     setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
     611        2388 :     setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
     612        2388 :     setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
     613        2388 :     setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
     614        2388 :     setOperationAction(ISD::FREM, MVT::v1f64, Expand);
     615        2388 :     setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
     616        2388 :     setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
     617        2388 :     setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
     618        2388 :     setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
     619        2388 :     setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
     620        2388 :     setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
     621        2388 :     setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
     622        2388 :     setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
     623        2388 :     setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
     624        2388 :     setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
     625        2388 :     setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
     626        2388 :     setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
     627             : 
     628        2388 :     setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
     629        2388 :     setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
     630        2388 :     setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
     631        2388 :     setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
     632        2388 :     setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
     633             : 
     634        2388 :     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
     635             : 
     636             :     // AArch64 doesn't have a direct vector ->f32 conversion instructions for
     637             :     // elements smaller than i32, so promote the input to i32 first.
     638        2388 :     setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
     639        2388 :     setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
     640        2388 :     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
     641        2388 :     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
     642             :     // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
     643             :     // -> v8f16 conversions.
     644        2388 :     setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
     645        2388 :     setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
     646        2388 :     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
     647        2388 :     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
     648             :     // Similarly, there is no direct i32 -> f64 vector conversion instruction.
     649        2388 :     setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
     650        2388 :     setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
     651        2388 :     setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
     652        2388 :     setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
     653             :     // Or, direct i32 -> f16 vector conversion.  Set it so custom, so the
     654             :     // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
     655        2388 :     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
     656        2388 :     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
     657             : 
     658        2388 :     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
     659        2388 :     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
     660             : 
     661        2388 :     setOperationAction(ISD::CTTZ,       MVT::v2i8,  Expand);
     662        2388 :     setOperationAction(ISD::CTTZ,       MVT::v4i16, Expand);
     663        2388 :     setOperationAction(ISD::CTTZ,       MVT::v2i32, Expand);
     664        2388 :     setOperationAction(ISD::CTTZ,       MVT::v1i64, Expand);
     665        2388 :     setOperationAction(ISD::CTTZ,       MVT::v16i8, Expand);
     666        2388 :     setOperationAction(ISD::CTTZ,       MVT::v8i16, Expand);
     667        2388 :     setOperationAction(ISD::CTTZ,       MVT::v4i32, Expand);
     668        2388 :     setOperationAction(ISD::CTTZ,       MVT::v2i64, Expand);
     669             : 
     670             :     // AArch64 doesn't have MUL.2d:
     671        1194 :     setOperationAction(ISD::MUL, MVT::v2i64, Expand);
     672             :     // Custom handling for some quad-vector types to detect MULL.
     673        2388 :     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
     674        2388 :     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
     675        2388 :     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
     676             : 
     677             :     // Vector reductions
     678        8358 :     for (MVT VT : MVT::integer_valuetypes()) {
     679       14328 :       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
     680       14328 :       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
     681       14328 :       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
     682       14328 :       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
     683       14328 :       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
     684             :     }
     685       15522 :     for (MVT VT : MVT::fp_valuetypes()) {
     686       14328 :       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
     687       14328 :       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
     688             :     }
     689             : 
     690        2388 :     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
     691        2388 :     setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
     692             :     // Likewise, narrowing and extending vector loads/stores aren't handled
     693             :     // directly.
     694      113430 :     for (MVT VT : MVT::vector_valuetypes()) {
     695      224472 :       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
     696             : 
     697      224472 :       setOperationAction(ISD::MULHS, VT, Expand);
     698      224472 :       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
     699      224472 :       setOperationAction(ISD::MULHU, VT, Expand);
     700      224472 :       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
     701             : 
     702      224472 :       setOperationAction(ISD::BSWAP, VT, Expand);
     703             : 
     704    10662420 :       for (MVT InnerVT : MVT::vector_valuetypes()) {
     705    21100368 :         setTruncStoreAction(VT, InnerVT, Expand);
     706    21100368 :         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
     707    21100368 :         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
     708    21100368 :         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
     709             :       }
     710             :     }
     711             : 
     712             :     // AArch64 has implementations of a lot of rounding-like FP operations.
     713       11940 :     for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
     714        7164 :       setOperationAction(ISD::FFLOOR, Ty, Legal);
     715        7164 :       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
     716        7164 :       setOperationAction(ISD::FCEIL, Ty, Legal);
     717        7164 :       setOperationAction(ISD::FRINT, Ty, Legal);
     718        7164 :       setOperationAction(ISD::FTRUNC, Ty, Legal);
     719        7164 :       setOperationAction(ISD::FROUND, Ty, Legal);
     720             :     }
     721             :   }
     722             : 
     723        1214 :   PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
     724        1214 : }
     725             : 
     726       16716 : void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
     727       33432 :   if (VT == MVT::v2f32 || VT == MVT::v4f16) {
     728        4776 :     setOperationAction(ISD::LOAD, VT, Promote);
     729        4776 :     AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
     730             : 
     731        4776 :     setOperationAction(ISD::STORE, VT, Promote);
     732        4776 :     AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
     733       14328 :   } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
     734        7164 :     setOperationAction(ISD::LOAD, VT, Promote);
     735        7164 :     AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
     736             : 
     737        7164 :     setOperationAction(ISD::STORE, VT, Promote);
     738        7164 :     AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
     739             :   }
     740             : 
     741             :   // Mark vector float intrinsics as expand.
     742       33432 :   if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
     743        7164 :     setOperationAction(ISD::FSIN, VT, Expand);
     744        7164 :     setOperationAction(ISD::FCOS, VT, Expand);
     745        7164 :     setOperationAction(ISD::FPOW, VT, Expand);
     746        7164 :     setOperationAction(ISD::FLOG, VT, Expand);
     747        7164 :     setOperationAction(ISD::FLOG2, VT, Expand);
     748        7164 :     setOperationAction(ISD::FLOG10, VT, Expand);
     749        7164 :     setOperationAction(ISD::FEXP, VT, Expand);
     750        7164 :     setOperationAction(ISD::FEXP2, VT, Expand);
     751             : 
     752             :     // But we do support custom-lowering for FCOPYSIGN.
     753        3582 :     setOperationAction(ISD::FCOPYSIGN, VT, Custom);
     754             :   }
     755             : 
     756       33432 :   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
     757       33432 :   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
     758       33432 :   setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
     759       33432 :   setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
     760       33432 :   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
     761       33432 :   setOperationAction(ISD::SRA, VT, Custom);
     762       33432 :   setOperationAction(ISD::SRL, VT, Custom);
     763       33432 :   setOperationAction(ISD::SHL, VT, Custom);
     764       33432 :   setOperationAction(ISD::AND, VT, Custom);
     765       33432 :   setOperationAction(ISD::OR, VT, Custom);
     766       33432 :   setOperationAction(ISD::SETCC, VT, Custom);
     767       33432 :   setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
     768             : 
     769       33432 :   setOperationAction(ISD::SELECT, VT, Expand);
     770       33432 :   setOperationAction(ISD::SELECT_CC, VT, Expand);
     771       33432 :   setOperationAction(ISD::VSELECT, VT, Expand);
     772     1872192 :   for (MVT InnerVT : MVT::all_valuetypes())
     773     3710952 :     setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
     774             : 
     775             :   // CNT supports only B element sizes.
     776       16716 :   if (VT != MVT::v8i8 && VT != MVT::v16i8)
     777       14328 :     setOperationAction(ISD::CTPOP, VT, Expand);
     778             : 
     779       33432 :   setOperationAction(ISD::UDIV, VT, Expand);
     780       33432 :   setOperationAction(ISD::SDIV, VT, Expand);
     781       33432 :   setOperationAction(ISD::UREM, VT, Expand);
     782       33432 :   setOperationAction(ISD::SREM, VT, Expand);
     783       33432 :   setOperationAction(ISD::FREM, VT, Expand);
     784             : 
     785       33432 :   setOperationAction(ISD::FP_TO_SINT, VT, Custom);
     786       33432 :   setOperationAction(ISD::FP_TO_UINT, VT, Custom);
     787             : 
     788       16716 :   if (!VT.isFloatingPoint())
     789        9552 :     setOperationAction(ISD::ABS, VT, Legal);
     790             : 
     791             :   // [SU][MIN|MAX] are available for all NEON types apart from i64.
     792       16716 :   if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
     793       64476 :     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
     794       57312 :       setOperationAction(Opcode, VT, Legal);
     795             : 
     796             :   // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
     797       23880 :   if (VT.isFloatingPoint() &&
     798       28636 :       (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
     799       38368 :     for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
     800       33572 :                             ISD::FMINNUM, ISD::FMAXNUM})
     801       38368 :       setOperationAction(Opcode, VT, Legal);
     802             : 
     803       16716 :   if (Subtarget->isLittleEndian()) {
     804       65576 :     for (unsigned im = (unsigned)ISD::PRE_INC;
     805       81970 :          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
     806      131152 :       setIndexedLoadAction(im, VT, Legal);
     807      131152 :       setIndexedStoreAction(im, VT, Legal);
     808             :     }
     809             :   }
     810       16716 : }
     811             : 
     812        8358 : void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
     813       16716 :   addRegisterClass(VT, &AArch64::FPR64RegClass);
     814        8358 :   addTypeForNEON(VT, MVT::v2i32);
     815        8358 : }
     816             : 
     817        8358 : void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
     818       16716 :   addRegisterClass(VT, &AArch64::FPR128RegClass);
     819        8358 :   addTypeForNEON(VT, MVT::v4i32);
     820        8358 : }
     821             : 
     822        3431 : EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
     823             :                                               EVT VT) const {
     824        3431 :   if (!VT.isVector())
     825        2990 :     return MVT::i32;
     826         441 :   return VT.changeVectorElementTypeToInteger();
     827             : }
     828             : 
     829         579 : static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
     830             :                                const APInt &Demanded,
     831             :                                TargetLowering::TargetLoweringOpt &TLO,
     832             :                                unsigned NewOpc) {
     833         579 :   uint64_t OldImm = Imm, NewImm, Enc;
     834         579 :   uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
     835             : 
     836             :   // Return if the immediate is already all zeros, all ones, a bimm32 or a
     837             :   // bimm64.
     838        1158 :   if (Imm == 0 || Imm == Mask ||
     839        1158 :       AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
     840             :     return false;
     841             : 
     842          23 :   unsigned EltSize = Size;
     843          23 :   uint64_t DemandedBits = Demanded.getZExtValue();
     844             : 
     845             :   // Clear bits that are not demanded.
     846          23 :   Imm &= DemandedBits;
     847             : 
     848             :   while (true) {
     849             :     // The goal here is to set the non-demanded bits in a way that minimizes
     850             :     // the number of switching between 0 and 1. In order to achieve this goal,
     851             :     // we set the non-demanded bits to the value of the preceding demanded bits.
     852             :     // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
     853             :     // non-demanded bit), we copy bit0 (1) to the least significant 'x',
     854             :     // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
     855             :     // The final result is 0b11000011.
     856          28 :     uint64_t NonDemandedBits = ~DemandedBits;
     857          28 :     uint64_t InvertedImm = ~Imm & DemandedBits;
     858          28 :     uint64_t RotatedImm =
     859          28 :         ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
     860             :         NonDemandedBits;
     861          28 :     uint64_t Sum = RotatedImm + NonDemandedBits;
     862          28 :     bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
     863          28 :     uint64_t Ones = (Sum + Carry) & NonDemandedBits;
     864          28 :     NewImm = (Imm | Ones) & Mask;
     865             : 
     866             :     // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
     867             :     // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
     868             :     // we halve the element size and continue the search.
     869          28 :     if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
     870             :       break;
     871             : 
     872             :     // We cannot shrink the element size any further if it is 2-bits.
     873          23 :     if (EltSize == 2)
     874             :       return false;
     875             : 
     876          23 :     EltSize /= 2;
     877          23 :     Mask >>= EltSize;
     878          23 :     uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
     879             : 
     880             :     // Return if there is mismatch in any of the demanded bits of Imm and Hi.
     881          23 :     if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
     882             :       return false;
     883             : 
     884             :     // Merge the upper and lower halves of Imm and DemandedBits.
     885           5 :     Imm |= Hi;
     886           5 :     DemandedBits |= DemandedBitsHi;
     887             :   }
     888             : 
     889             :   ++NumOptimizedImms;
     890             : 
     891             :   // Replicate the element across the register width.
     892          10 :   while (EltSize < Size) {
     893           5 :     NewImm |= NewImm << EltSize;
     894           5 :     EltSize *= 2;
     895             :   }
     896             : 
     897             :   (void)OldImm;
     898             :   assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
     899             :          "demanded bits should never be altered");
     900             :   assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
     901             : 
     902             :   // Create the new constant immediate node.
     903          10 :   EVT VT = Op.getValueType();
     904           5 :   SDLoc DL(Op);
     905           5 :   SDValue New;
     906             : 
     907             :   // If the new constant immediate is all-zeros or all-ones, let the target
     908             :   // independent DAG combine optimize this node.
     909           5 :   if (NewImm == 0 || NewImm == OrigMask) {
     910           4 :     New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
     911           3 :                           TLO.DAG.getConstant(NewImm, DL, VT));
     912             :   // Otherwise, create a machine node so that target independent DAG combine
     913             :   // doesn't undo this optimization.
     914             :   } else {
     915           4 :     Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
     916           8 :     SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
     917           4 :     New = SDValue(
     918           8 :         TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
     919             :   }
     920             : 
     921           5 :   return TLO.CombineTo(Op, New);
     922             : }
     923             : 
     924        6375 : bool AArch64TargetLowering::targetShrinkDemandedConstant(
     925             :     SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
     926             :   // Delay this optimization to as late as possible.
     927        6375 :   if (!TLO.LegalOps)
     928             :     return false;
     929             : 
     930        3300 :   if (!EnableOptimizeLogicalImm)
     931             :     return false;
     932             : 
     933        6600 :   EVT VT = Op.getValueType();
     934        3300 :   if (VT.isVector())
     935             :     return false;
     936             : 
     937        2491 :   unsigned Size = VT.getSizeInBits();
     938             :   assert((Size == 32 || Size == 64) &&
     939             :          "i32 or i64 is expected after legalization.");
     940             : 
     941             :   // Exit early if we demand all bits.
     942        2491 :   if (Demanded.countPopulation() == Size)
     943             :     return false;
     944             : 
     945             :   unsigned NewOpc;
     946        1300 :   switch (Op.getOpcode()) {
     947             :   default:
     948             :     return false;
     949         592 :   case ISD::AND:
     950         592 :     NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
     951             :     break;
     952          56 :   case ISD::OR:
     953          56 :     NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
     954             :     break;
     955           2 :   case ISD::XOR:
     956           2 :     NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
     957             :     break;
     958             :   }
     959        1879 :   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
     960             :   if (!C)
     961             :     return false;
     962         579 :   uint64_t Imm = C->getZExtValue();
     963         579 :   return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
     964             : }
     965             : 
     966             : /// computeKnownBitsForTargetNode - Determine which of the bits specified in
     967             : /// Mask are known to be either zero or one and return them Known.
     968        5993 : void AArch64TargetLowering::computeKnownBitsForTargetNode(
     969             :     const SDValue Op, KnownBits &Known,
     970             :     const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
     971       11986 :   switch (Op.getOpcode()) {
     972             :   default:
     973             :     break;
     974         321 :   case AArch64ISD::CSEL: {
     975         642 :     KnownBits Known2;
     976         642 :     DAG.computeKnownBits(Op->getOperand(0), Known, Depth + 1);
     977         642 :     DAG.computeKnownBits(Op->getOperand(1), Known2, Depth + 1);
     978         642 :     Known.Zero &= Known2.Zero;
     979         642 :     Known.One &= Known2.One;
     980             :     break;
     981             :   }
     982        1191 :   case ISD::INTRINSIC_W_CHAIN: {
     983        3573 :     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
     984        1191 :     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
     985        1191 :     switch (IntID) {
     986             :     default: return;
     987        1011 :     case Intrinsic::aarch64_ldaxr:
     988             :     case Intrinsic::aarch64_ldxr: {
     989        1011 :       unsigned BitWidth = Known.getBitWidth();
     990        1011 :       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
     991        1011 :       unsigned MemBits = VT.getScalarSizeInBits();
     992        3033 :       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
     993             :       return;
     994             :     }
     995             :     }
     996             :     break;
     997             :   }
     998        1208 :   case ISD::INTRINSIC_WO_CHAIN:
     999             :   case ISD::INTRINSIC_VOID: {
    1000        4832 :     unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
    1001        1208 :     switch (IntNo) {
    1002             :     default:
    1003             :       break;
    1004          24 :     case Intrinsic::aarch64_neon_umaxv:
    1005             :     case Intrinsic::aarch64_neon_uminv: {
    1006             :       // Figure out the datatype of the vector operand. The UMINV instruction
    1007             :       // will zero extend the result, so we can mark as known zero all the
    1008             :       // bits larger than the element datatype. 32-bit or larget doesn't need
    1009             :       // this as those are legal types and will be handled by isel directly.
    1010          72 :       MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
    1011          24 :       unsigned BitWidth = Known.getBitWidth();
    1012          24 :       if (VT == MVT::v8i8 || VT == MVT::v16i8) {
    1013             :         assert(BitWidth >= 8 && "Unexpected width!");
    1014          32 :         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
    1015          32 :         Known.Zero |= Mask;
    1016          12 :       } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
    1017             :         assert(BitWidth >= 16 && "Unexpected width!");
    1018          16 :         APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
    1019          16 :         Known.Zero |= Mask;
    1020             :       }
    1021             :       break;
    1022             :     } break;
    1023             :     }
    1024             :   }
    1025             :   }
    1026             : }
    1027             : 
    1028        3441 : MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
    1029             :                                                   EVT) const {
    1030        3441 :   return MVT::i64;
    1031             : }
    1032             : 
    1033        2150 : bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
    1034             :                                                            unsigned AddrSpace,
    1035             :                                                            unsigned Align,
    1036             :                                                            bool *Fast) const {
    1037        2150 :   if (Subtarget->requiresStrictAlign())
    1038             :     return false;
    1039             : 
    1040        1864 :   if (Fast) {
    1041             :     // Some CPUs are fine with unaligned stores except for 128-bit ones.
    1042         326 :     *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
    1043             :             // See comments in performSTORECombine() for more details about
    1044             :             // these conditions.
    1045             : 
    1046             :             // Code that uses clang vector extensions can mark that it
    1047             :             // wants unaligned accesses to be treated as fast by
    1048             :             // underspecifying alignment to be 1 or 2.
    1049         140 :             Align <= 2 ||
    1050             : 
    1051             :             // Disregard v2i64. Memcpy lowering produces those and splitting
    1052             :             // them regresses performance on micro-benchmarks and olden/bh.
    1053          14 :             VT == MVT::v2i64;
    1054             :   }
    1055             :   return true;
    1056             : }
    1057             : 
    1058             : FastISel *
    1059        1214 : AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
    1060             :                                       const TargetLibraryInfo *libInfo) const {
    1061        1214 :   return AArch64::createFastISel(funcInfo, libInfo);
    1062             : }
    1063             : 
    1064           0 : const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
    1065           0 :   switch ((AArch64ISD::NodeType)Opcode) {
    1066             :   case AArch64ISD::FIRST_NUMBER:      break;
    1067             :   case AArch64ISD::CALL:              return "AArch64ISD::CALL";
    1068           0 :   case AArch64ISD::ADRP:              return "AArch64ISD::ADRP";
    1069           0 :   case AArch64ISD::ADDlow:            return "AArch64ISD::ADDlow";
    1070           0 :   case AArch64ISD::LOADgot:           return "AArch64ISD::LOADgot";
    1071           0 :   case AArch64ISD::RET_FLAG:          return "AArch64ISD::RET_FLAG";
    1072           0 :   case AArch64ISD::BRCOND:            return "AArch64ISD::BRCOND";
    1073           0 :   case AArch64ISD::CSEL:              return "AArch64ISD::CSEL";
    1074           0 :   case AArch64ISD::FCSEL:             return "AArch64ISD::FCSEL";
    1075           0 :   case AArch64ISD::CSINV:             return "AArch64ISD::CSINV";
    1076           0 :   case AArch64ISD::CSNEG:             return "AArch64ISD::CSNEG";
    1077           0 :   case AArch64ISD::CSINC:             return "AArch64ISD::CSINC";
    1078           0 :   case AArch64ISD::THREAD_POINTER:    return "AArch64ISD::THREAD_POINTER";
    1079           0 :   case AArch64ISD::TLSDESC_CALLSEQ:   return "AArch64ISD::TLSDESC_CALLSEQ";
    1080           0 :   case AArch64ISD::ADC:               return "AArch64ISD::ADC";
    1081           0 :   case AArch64ISD::SBC:               return "AArch64ISD::SBC";
    1082           0 :   case AArch64ISD::ADDS:              return "AArch64ISD::ADDS";
    1083           0 :   case AArch64ISD::SUBS:              return "AArch64ISD::SUBS";
    1084           0 :   case AArch64ISD::ADCS:              return "AArch64ISD::ADCS";
    1085           0 :   case AArch64ISD::SBCS:              return "AArch64ISD::SBCS";
    1086           0 :   case AArch64ISD::ANDS:              return "AArch64ISD::ANDS";
    1087           0 :   case AArch64ISD::CCMP:              return "AArch64ISD::CCMP";
    1088           0 :   case AArch64ISD::CCMN:              return "AArch64ISD::CCMN";
    1089           0 :   case AArch64ISD::FCCMP:             return "AArch64ISD::FCCMP";
    1090           0 :   case AArch64ISD::FCMP:              return "AArch64ISD::FCMP";
    1091           0 :   case AArch64ISD::DUP:               return "AArch64ISD::DUP";
    1092           0 :   case AArch64ISD::DUPLANE8:          return "AArch64ISD::DUPLANE8";
    1093           0 :   case AArch64ISD::DUPLANE16:         return "AArch64ISD::DUPLANE16";
    1094           0 :   case AArch64ISD::DUPLANE32:         return "AArch64ISD::DUPLANE32";
    1095           0 :   case AArch64ISD::DUPLANE64:         return "AArch64ISD::DUPLANE64";
    1096           0 :   case AArch64ISD::MOVI:              return "AArch64ISD::MOVI";
    1097           0 :   case AArch64ISD::MOVIshift:         return "AArch64ISD::MOVIshift";
    1098           0 :   case AArch64ISD::MOVIedit:          return "AArch64ISD::MOVIedit";
    1099           0 :   case AArch64ISD::MOVImsl:           return "AArch64ISD::MOVImsl";
    1100           0 :   case AArch64ISD::FMOV:              return "AArch64ISD::FMOV";
    1101           0 :   case AArch64ISD::MVNIshift:         return "AArch64ISD::MVNIshift";
    1102           0 :   case AArch64ISD::MVNImsl:           return "AArch64ISD::MVNImsl";
    1103           0 :   case AArch64ISD::BICi:              return "AArch64ISD::BICi";
    1104           0 :   case AArch64ISD::ORRi:              return "AArch64ISD::ORRi";
    1105           0 :   case AArch64ISD::BSL:               return "AArch64ISD::BSL";
    1106           0 :   case AArch64ISD::NEG:               return "AArch64ISD::NEG";
    1107           0 :   case AArch64ISD::EXTR:              return "AArch64ISD::EXTR";
    1108           0 :   case AArch64ISD::ZIP1:              return "AArch64ISD::ZIP1";
    1109           0 :   case AArch64ISD::ZIP2:              return "AArch64ISD::ZIP2";
    1110           0 :   case AArch64ISD::UZP1:              return "AArch64ISD::UZP1";
    1111           0 :   case AArch64ISD::UZP2:              return "AArch64ISD::UZP2";
    1112           0 :   case AArch64ISD::TRN1:              return "AArch64ISD::TRN1";
    1113           0 :   case AArch64ISD::TRN2:              return "AArch64ISD::TRN2";
    1114           0 :   case AArch64ISD::REV16:             return "AArch64ISD::REV16";
    1115           0 :   case AArch64ISD::REV32:             return "AArch64ISD::REV32";
    1116           0 :   case AArch64ISD::REV64:             return "AArch64ISD::REV64";
    1117           0 :   case AArch64ISD::EXT:               return "AArch64ISD::EXT";
    1118           0 :   case AArch64ISD::VSHL:              return "AArch64ISD::VSHL";
    1119           0 :   case AArch64ISD::VLSHR:             return "AArch64ISD::VLSHR";
    1120           0 :   case AArch64ISD::VASHR:             return "AArch64ISD::VASHR";
    1121           0 :   case AArch64ISD::CMEQ:              return "AArch64ISD::CMEQ";
    1122           0 :   case AArch64ISD::CMGE:              return "AArch64ISD::CMGE";
    1123           0 :   case AArch64ISD::CMGT:              return "AArch64ISD::CMGT";
    1124           0 :   case AArch64ISD::CMHI:              return "AArch64ISD::CMHI";
    1125           0 :   case AArch64ISD::CMHS:              return "AArch64ISD::CMHS";
    1126           0 :   case AArch64ISD::FCMEQ:             return "AArch64ISD::FCMEQ";
    1127           0 :   case AArch64ISD::FCMGE:             return "AArch64ISD::FCMGE";
    1128           0 :   case AArch64ISD::FCMGT:             return "AArch64ISD::FCMGT";
    1129           0 :   case AArch64ISD::CMEQz:             return "AArch64ISD::CMEQz";
    1130           0 :   case AArch64ISD::CMGEz:             return "AArch64ISD::CMGEz";
    1131           0 :   case AArch64ISD::CMGTz:             return "AArch64ISD::CMGTz";
    1132           0 :   case AArch64ISD::CMLEz:             return "AArch64ISD::CMLEz";
    1133           0 :   case AArch64ISD::CMLTz:             return "AArch64ISD::CMLTz";
    1134           0 :   case AArch64ISD::FCMEQz:            return "AArch64ISD::FCMEQz";
    1135           0 :   case AArch64ISD::FCMGEz:            return "AArch64ISD::FCMGEz";
    1136           0 :   case AArch64ISD::FCMGTz:            return "AArch64ISD::FCMGTz";
    1137           0 :   case AArch64ISD::FCMLEz:            return "AArch64ISD::FCMLEz";
    1138           0 :   case AArch64ISD::FCMLTz:            return "AArch64ISD::FCMLTz";
    1139           0 :   case AArch64ISD::SADDV:             return "AArch64ISD::SADDV";
    1140           0 :   case AArch64ISD::UADDV:             return "AArch64ISD::UADDV";
    1141           0 :   case AArch64ISD::SMINV:             return "AArch64ISD::SMINV";
    1142           0 :   case AArch64ISD::UMINV:             return "AArch64ISD::UMINV";
    1143           0 :   case AArch64ISD::SMAXV:             return "AArch64ISD::SMAXV";
    1144           0 :   case AArch64ISD::UMAXV:             return "AArch64ISD::UMAXV";
    1145           0 :   case AArch64ISD::NOT:               return "AArch64ISD::NOT";
    1146           0 :   case AArch64ISD::BIT:               return "AArch64ISD::BIT";
    1147           0 :   case AArch64ISD::CBZ:               return "AArch64ISD::CBZ";
    1148           0 :   case AArch64ISD::CBNZ:              return "AArch64ISD::CBNZ";
    1149           0 :   case AArch64ISD::TBZ:               return "AArch64ISD::TBZ";
    1150           0 :   case AArch64ISD::TBNZ:              return "AArch64ISD::TBNZ";
    1151           0 :   case AArch64ISD::TC_RETURN:         return "AArch64ISD::TC_RETURN";
    1152           0 :   case AArch64ISD::PREFETCH:          return "AArch64ISD::PREFETCH";
    1153           0 :   case AArch64ISD::SITOF:             return "AArch64ISD::SITOF";
    1154           0 :   case AArch64ISD::UITOF:             return "AArch64ISD::UITOF";
    1155           0 :   case AArch64ISD::NVCAST:            return "AArch64ISD::NVCAST";
    1156           0 :   case AArch64ISD::SQSHL_I:           return "AArch64ISD::SQSHL_I";
    1157           0 :   case AArch64ISD::UQSHL_I:           return "AArch64ISD::UQSHL_I";
    1158           0 :   case AArch64ISD::SRSHR_I:           return "AArch64ISD::SRSHR_I";
    1159           0 :   case AArch64ISD::URSHR_I:           return "AArch64ISD::URSHR_I";
    1160           0 :   case AArch64ISD::SQSHLU_I:          return "AArch64ISD::SQSHLU_I";
    1161           0 :   case AArch64ISD::WrapperLarge:      return "AArch64ISD::WrapperLarge";
    1162           0 :   case AArch64ISD::LD2post:           return "AArch64ISD::LD2post";
    1163           0 :   case AArch64ISD::LD3post:           return "AArch64ISD::LD3post";
    1164           0 :   case AArch64ISD::LD4post:           return "AArch64ISD::LD4post";
    1165           0 :   case AArch64ISD::ST2post:           return "AArch64ISD::ST2post";
    1166           0 :   case AArch64ISD::ST3post:           return "AArch64ISD::ST3post";
    1167           0 :   case AArch64ISD::ST4post:           return "AArch64ISD::ST4post";
    1168           0 :   case AArch64ISD::LD1x2post:         return "AArch64ISD::LD1x2post";
    1169           0 :   case AArch64ISD::LD1x3post:         return "AArch64ISD::LD1x3post";
    1170           0 :   case AArch64ISD::LD1x4post:         return "AArch64ISD::LD1x4post";
    1171           0 :   case AArch64ISD::ST1x2post:         return "AArch64ISD::ST1x2post";
    1172           0 :   case AArch64ISD::ST1x3post:         return "AArch64ISD::ST1x3post";
    1173           0 :   case AArch64ISD::ST1x4post:         return "AArch64ISD::ST1x4post";
    1174           0 :   case AArch64ISD::LD1DUPpost:        return "AArch64ISD::LD1DUPpost";
    1175           0 :   case AArch64ISD::LD2DUPpost:        return "AArch64ISD::LD2DUPpost";
    1176           0 :   case AArch64ISD::LD3DUPpost:        return "AArch64ISD::LD3DUPpost";
    1177           0 :   case AArch64ISD::LD4DUPpost:        return "AArch64ISD::LD4DUPpost";
    1178           0 :   case AArch64ISD::LD1LANEpost:       return "AArch64ISD::LD1LANEpost";
    1179           0 :   case AArch64ISD::LD2LANEpost:       return "AArch64ISD::LD2LANEpost";
    1180           0 :   case AArch64ISD::LD3LANEpost:       return "AArch64ISD::LD3LANEpost";
    1181           0 :   case AArch64ISD::LD4LANEpost:       return "AArch64ISD::LD4LANEpost";
    1182           0 :   case AArch64ISD::ST2LANEpost:       return "AArch64ISD::ST2LANEpost";
    1183           0 :   case AArch64ISD::ST3LANEpost:       return "AArch64ISD::ST3LANEpost";
    1184           0 :   case AArch64ISD::ST4LANEpost:       return "AArch64ISD::ST4LANEpost";
    1185           0 :   case AArch64ISD::SMULL:             return "AArch64ISD::SMULL";
    1186           0 :   case AArch64ISD::UMULL:             return "AArch64ISD::UMULL";
    1187           0 :   case AArch64ISD::FRECPE:            return "AArch64ISD::FRECPE";
    1188           0 :   case AArch64ISD::FRECPS:            return "AArch64ISD::FRECPS";
    1189           0 :   case AArch64ISD::FRSQRTE:           return "AArch64ISD::FRSQRTE";
    1190           0 :   case AArch64ISD::FRSQRTS:           return "AArch64ISD::FRSQRTS";
    1191             :   }
    1192           0 :   return nullptr;
    1193             : }
    1194             : 
    1195             : MachineBasicBlock *
    1196           3 : AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
    1197             :                                     MachineBasicBlock *MBB) const {
    1198             :   // We materialise the F128CSEL pseudo-instruction as some control flow and a
    1199             :   // phi node:
    1200             : 
    1201             :   // OrigBB:
    1202             :   //     [... previous instrs leading to comparison ...]
    1203             :   //     b.ne TrueBB
    1204             :   //     b EndBB
    1205             :   // TrueBB:
    1206             :   //     ; Fallthrough
    1207             :   // EndBB:
    1208             :   //     Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
    1209             : 
    1210           3 :   MachineFunction *MF = MBB->getParent();
    1211           3 :   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
    1212           3 :   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
    1213           9 :   DebugLoc DL = MI.getDebugLoc();
    1214           9 :   MachineFunction::iterator It = ++MBB->getIterator();
    1215             : 
    1216           3 :   unsigned DestReg = MI.getOperand(0).getReg();
    1217           3 :   unsigned IfTrueReg = MI.getOperand(1).getReg();
    1218           3 :   unsigned IfFalseReg = MI.getOperand(2).getReg();
    1219           3 :   unsigned CondCode = MI.getOperand(3).getImm();
    1220           6 :   bool NZCVKilled = MI.getOperand(4).isKill();
    1221             : 
    1222           3 :   MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
    1223           3 :   MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
    1224           3 :   MF->insert(It, TrueBB);
    1225           3 :   MF->insert(It, EndBB);
    1226             : 
    1227             :   // Transfer rest of current basic-block to EndBB
    1228          15 :   EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
    1229             :                 MBB->end());
    1230           3 :   EndBB->transferSuccessorsAndUpdatePHIs(MBB);
    1231             : 
    1232          15 :   BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
    1233          12 :   BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
    1234           3 :   MBB->addSuccessor(TrueBB);
    1235           3 :   MBB->addSuccessor(EndBB);
    1236             : 
    1237             :   // TrueBB falls through to the end.
    1238           3 :   TrueBB->addSuccessor(EndBB);
    1239             : 
    1240           3 :   if (!NZCVKilled) {
    1241           6 :     TrueBB->addLiveIn(AArch64::NZCV);
    1242           3 :     EndBB->addLiveIn(AArch64::NZCV);
    1243             :   }
    1244             : 
    1245           9 :   BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
    1246           3 :       .addReg(IfTrueReg)
    1247           3 :       .addMBB(TrueBB)
    1248           3 :       .addReg(IfFalseReg)
    1249           3 :       .addMBB(MBB);
    1250             : 
    1251           3 :   MI.eraseFromParent();
    1252           6 :   return EndBB;
    1253             : }
    1254             : 
    1255          67 : MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
    1256             :     MachineInstr &MI, MachineBasicBlock *BB) const {
    1257         134 :   switch (MI.getOpcode()) {
    1258           0 :   default:
    1259             : #ifndef NDEBUG
    1260             :     MI.dump();
    1261             : #endif
    1262           0 :     llvm_unreachable("Unexpected instruction for custom inserter!");
    1263             : 
    1264           3 :   case AArch64::F128CSEL:
    1265           3 :     return EmitF128CSEL(MI, BB);
    1266             : 
    1267          64 :   case TargetOpcode::STACKMAP:
    1268             :   case TargetOpcode::PATCHPOINT:
    1269          64 :     return emitPatchPoint(MI, BB);
    1270             :   }
    1271             : }
    1272             : 
    1273             : //===----------------------------------------------------------------------===//
    1274             : // AArch64 Lowering private implementation.
    1275             : //===----------------------------------------------------------------------===//
    1276             : 
    1277             : //===----------------------------------------------------------------------===//
    1278             : // Lowering Code
    1279             : //===----------------------------------------------------------------------===//
    1280             : 
    1281             : /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
    1282             : /// CC
    1283        1038 : static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
    1284        1038 :   switch (CC) {
    1285           0 :   default:
    1286           0 :     llvm_unreachable("Unknown condition code!");
    1287             :   case ISD::SETNE:
    1288             :     return AArch64CC::NE;
    1289         190 :   case ISD::SETEQ:
    1290         190 :     return AArch64CC::EQ;
    1291          95 :   case ISD::SETGT:
    1292          95 :     return AArch64CC::GT;
    1293          58 :   case ISD::SETGE:
    1294          58 :     return AArch64CC::GE;
    1295         129 :   case ISD::SETLT:
    1296         129 :     return AArch64CC::LT;
    1297          77 :   case ISD::SETLE:
    1298          77 :     return AArch64CC::LE;
    1299         103 :   case ISD::SETUGT:
    1300         103 :     return AArch64CC::HI;
    1301          39 :   case ISD::SETUGE:
    1302          39 :     return AArch64CC::HS;
    1303          51 :   case ISD::SETULT:
    1304          51 :     return AArch64CC::LO;
    1305          64 :   case ISD::SETULE:
    1306          64 :     return AArch64CC::LS;
    1307             :   }
    1308             : }
    1309             : 
    1310             : /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
    1311         514 : static void changeFPCCToAArch64CC(ISD::CondCode CC,
    1312             :                                   AArch64CC::CondCode &CondCode,
    1313             :                                   AArch64CC::CondCode &CondCode2) {
    1314         514 :   CondCode2 = AArch64CC::AL;
    1315         514 :   switch (CC) {
    1316           0 :   default:
    1317           0 :     llvm_unreachable("Unknown FP condition!");
    1318          73 :   case ISD::SETEQ:
    1319             :   case ISD::SETOEQ:
    1320          73 :     CondCode = AArch64CC::EQ;
    1321          73 :     break;
    1322          38 :   case ISD::SETGT:
    1323             :   case ISD::SETOGT:
    1324          38 :     CondCode = AArch64CC::GT;
    1325          38 :     break;
    1326          39 :   case ISD::SETGE:
    1327             :   case ISD::SETOGE:
    1328          39 :     CondCode = AArch64CC::GE;
    1329          39 :     break;
    1330          56 :   case ISD::SETOLT:
    1331          56 :     CondCode = AArch64CC::MI;
    1332          56 :     break;
    1333          37 :   case ISD::SETOLE:
    1334          37 :     CondCode = AArch64CC::LS;
    1335          37 :     break;
    1336          37 :   case ISD::SETONE:
    1337          37 :     CondCode = AArch64CC::MI;
    1338          37 :     CondCode2 = AArch64CC::GT;
    1339          37 :     break;
    1340          23 :   case ISD::SETO:
    1341          23 :     CondCode = AArch64CC::VC;
    1342          23 :     break;
    1343          23 :   case ISD::SETUO:
    1344          23 :     CondCode = AArch64CC::VS;
    1345          23 :     break;
    1346          27 :   case ISD::SETUEQ:
    1347          27 :     CondCode = AArch64CC::EQ;
    1348          27 :     CondCode2 = AArch64CC::VS;
    1349          27 :     break;
    1350          23 :   case ISD::SETUGT:
    1351          23 :     CondCode = AArch64CC::HI;
    1352          23 :     break;
    1353          27 :   case ISD::SETUGE:
    1354          27 :     CondCode = AArch64CC::PL;
    1355          27 :     break;
    1356          25 :   case ISD::SETLT:
    1357             :   case ISD::SETULT:
    1358          25 :     CondCode = AArch64CC::LT;
    1359          25 :     break;
    1360          27 :   case ISD::SETLE:
    1361             :   case ISD::SETULE:
    1362          27 :     CondCode = AArch64CC::LE;
    1363          27 :     break;
    1364          59 :   case ISD::SETNE:
    1365             :   case ISD::SETUNE:
    1366          59 :     CondCode = AArch64CC::NE;
    1367          59 :     break;
    1368             :   }
    1369         514 : }
    1370             : 
    1371             : /// Convert a DAG fp condition code to an AArch64 CC.
    1372             : /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
    1373             : /// should be AND'ed instead of OR'ed.
    1374          28 : static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
    1375             :                                      AArch64CC::CondCode &CondCode,
    1376             :                                      AArch64CC::CondCode &CondCode2) {
    1377          28 :   CondCode2 = AArch64CC::AL;
    1378          28 :   switch (CC) {
    1379          17 :   default:
    1380          17 :     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
    1381             :     assert(CondCode2 == AArch64CC::AL);
    1382          17 :     break;
    1383           7 :   case ISD::SETONE:
    1384             :     // (a one b)
    1385             :     // == ((a olt b) || (a ogt b))
    1386             :     // == ((a ord b) && (a une b))
    1387           7 :     CondCode = AArch64CC::VC;
    1388           7 :     CondCode2 = AArch64CC::NE;
    1389           7 :     break;
    1390           4 :   case ISD::SETUEQ:
    1391             :     // (a ueq b)
    1392             :     // == ((a uno b) || (a oeq b))
    1393             :     // == ((a ule b) && (a uge b))
    1394           4 :     CondCode = AArch64CC::PL;
    1395           4 :     CondCode2 = AArch64CC::LE;
    1396           4 :     break;
    1397             :   }
    1398          28 : }
    1399             : 
    1400             : /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
    1401             : /// CC usable with the vector instructions. Fewer operations are available
    1402             : /// without a real NZCV register, so we have to use less efficient combinations
    1403             : /// to get the same effect.
    1404         121 : static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
    1405             :                                         AArch64CC::CondCode &CondCode,
    1406             :                                         AArch64CC::CondCode &CondCode2,
    1407             :                                         bool &Invert) {
    1408         121 :   Invert = false;
    1409         121 :   switch (CC) {
    1410          79 :   default:
    1411             :     // Mostly the scalar mappings work fine.
    1412          79 :     changeFPCCToAArch64CC(CC, CondCode, CondCode2);
    1413          79 :     break;
    1414           6 :   case ISD::SETUO:
    1415           6 :     Invert = true;
    1416             :     LLVM_FALLTHROUGH;
    1417          12 :   case ISD::SETO:
    1418          12 :     CondCode = AArch64CC::MI;
    1419          12 :     CondCode2 = AArch64CC::GE;
    1420          12 :     break;
    1421          30 :   case ISD::SETUEQ:
    1422             :   case ISD::SETULT:
    1423             :   case ISD::SETULE:
    1424             :   case ISD::SETUGT:
    1425             :   case ISD::SETUGE:
    1426             :     // All of the compare-mask comparisons are ordered, but we can switch
    1427             :     // between the two by a double inversion. E.g. ULE == !OGT.
    1428          30 :     Invert = true;
    1429          30 :     changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
    1430          30 :     break;
    1431             :   }
    1432         121 : }
    1433             : 
    1434             : static bool isLegalArithImmed(uint64_t C) {
    1435             :   // Matches AArch64DAGToDAGISel::SelectArithImmed().
    1436         422 :   bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
    1437             :   DEBUG(dbgs() << "Is imm " << C << " legal: " << (IsLegal ? "yes\n" : "no\n"));
    1438             :   return IsLegal;
    1439             : }
    1440             : 
    1441        1040 : static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
    1442             :                               const SDLoc &dl, SelectionDAG &DAG) {
    1443        2080 :   EVT VT = LHS.getValueType();
    1444             :   const bool FullFP16 =
    1445        2080 :     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
    1446             : 
    1447        1040 :   if (VT.isFloatingPoint()) {
    1448             :     assert(VT != MVT::f128);
    1449         442 :     if (VT == MVT::f16 && !FullFP16) {
    1450           6 :       LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
    1451           6 :       RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
    1452           3 :       VT = MVT::f32;
    1453             :     }
    1454         366 :     return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
    1455             :   }
    1456             : 
    1457             :   // The CMP instruction is just an alias for SUBS, and representing it as
    1458             :   // SUBS means that it's possible to get CSE with subtract operations.
    1459             :   // A later phase can perform the optimization of setting the destination
    1460             :   // register to WZR/XZR if it ends up being unused.
    1461         674 :   unsigned Opcode = AArch64ISD::SUBS;
    1462             : 
    1463        1364 :   if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
    1464           8 :       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
    1465             :     // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
    1466             :     // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
    1467             :     // can be set differently by this operation. It comes down to whether
    1468             :     // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
    1469             :     // everything is fine. If not then the optimization is wrong. Thus general
    1470             :     // comparisons are only valid if op2 != 0.
    1471             : 
    1472             :     // So, finally, the only LLVM-native comparisons that don't mention C and V
    1473             :     // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
    1474             :     // the absence of information about op2.
    1475           6 :     Opcode = AArch64ISD::ADDS;
    1476          12 :     RHS = RHS.getOperand(1);
    1477        1402 :   } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
    1478          24 :              !isUnsignedIntSetCC(CC)) {
    1479             :     // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
    1480             :     // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
    1481             :     // of the signed comparisons.
    1482          24 :     Opcode = AArch64ISD::ANDS;
    1483          48 :     RHS = LHS.getOperand(1);
    1484          48 :     LHS = LHS.getOperand(0);
    1485             :   }
    1486             : 
    1487        1348 :   return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
    1488        1348 :       .getValue(1);
    1489             : }
    1490             : 
    1491             : /// \defgroup AArch64CCMP CMP;CCMP matching
    1492             : ///
    1493             : /// These functions deal with the formation of CMP;CCMP;... sequences.
    1494             : /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
    1495             : /// a comparison. They set the NZCV flags to a predefined value if their
    1496             : /// predicate is false. This allows to express arbitrary conjunctions, for
    1497             : /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
    1498             : /// expressed as:
    1499             : ///   cmp A
    1500             : ///   ccmp B, inv(CB), CA
    1501             : ///   check for CB flags
    1502             : ///
    1503             : /// In general we can create code for arbitrary "... (and (and A B) C)"
    1504             : /// sequences. We can also implement some "or" expressions, because "(or A B)"
    1505             : /// is equivalent to "not (and (not A) (not B))" and we can implement some
    1506             : /// negation operations:
    1507             : /// We can negate the results of a single comparison by inverting the flags
    1508             : /// used when the predicate fails and inverting the flags tested in the next
    1509             : /// instruction; We can also negate the results of the whole previous
    1510             : /// conditional compare sequence by inverting the flags tested in the next
    1511             : /// instruction. However there is no way to negate the result of a partial
    1512             : /// sequence.
    1513             : ///
    1514             : /// Therefore on encountering an "or" expression we can negate the subtree on
    1515             : /// one side and have to be able to push the negate to the leafs of the subtree
    1516             : /// on the other side (see also the comments in code). As complete example:
    1517             : /// "or (or (setCA (cmp A)) (setCB (cmp B)))
    1518             : ///     (and (setCC (cmp C)) (setCD (cmp D)))"
    1519             : /// is transformed to
    1520             : /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
    1521             : ///           (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
    1522             : /// and implemented as:
    1523             : ///   cmp C
    1524             : ///   ccmp D, inv(CD), CC
    1525             : ///   ccmp A, CA, inv(CD)
    1526             : ///   ccmp B, CB, inv(CA)
    1527             : ///   check for CB flags
    1528             : /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
    1529             : /// by conditional compare sequences.
    1530             : /// @{
    1531             : 
    1532             : /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
    1533          38 : static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
    1534             :                                          ISD::CondCode CC, SDValue CCOp,
    1535             :                                          AArch64CC::CondCode Predicate,
    1536             :                                          AArch64CC::CondCode OutCC,
    1537             :                                          const SDLoc &DL, SelectionDAG &DAG) {
    1538          38 :   unsigned Opcode = 0;
    1539             :   const bool FullFP16 =
    1540          76 :     static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
    1541             : 
    1542          76 :   if (LHS.getValueType().isFloatingPoint()) {
    1543             :     assert(LHS.getValueType() != MVT::f128);
    1544          56 :     if (LHS.getValueType() == MVT::f16 && !FullFP16) {
    1545           8 :       LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
    1546           8 :       RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
    1547             :     }
    1548             :     Opcode = AArch64ISD::FCCMP;
    1549          24 :   } else if (RHS.getOpcode() == ISD::SUB) {
    1550           0 :     SDValue SubOp0 = RHS.getOperand(0);
    1551           0 :     if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
    1552             :       // See emitComparison() on why we can only do this for SETEQ and SETNE.
    1553           0 :       Opcode = AArch64ISD::CCMN;
    1554           0 :       RHS = RHS.getOperand(1);
    1555             :     }
    1556             :   }
    1557             :   if (Opcode == 0)
    1558             :     Opcode = AArch64ISD::CCMP;
    1559             : 
    1560          38 :   SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
    1561          38 :   AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
    1562          38 :   unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
    1563          38 :   SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
    1564          38 :   return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
    1565             : }
    1566             : 
    1567             : /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
    1568             : /// CanPushNegate is set to true if we can push a negate operation through
    1569             : /// the tree in a was that we are left with AND operations and negate operations
    1570             : /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
    1571             : /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
    1572             : /// brought into such a form.
    1573         218 : static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
    1574             :                                          unsigned Depth = 0) {
    1575         436 :   if (!Val.hasOneUse())
    1576             :     return false;
    1577         400 :   unsigned Opcode = Val->getOpcode();
    1578         200 :   if (Opcode == ISD::SETCC) {
    1579         300 :     if (Val->getOperand(0).getValueType() == MVT::f128)
    1580             :       return false;
    1581          74 :     CanNegate = true;
    1582             :     return true;
    1583             :   }
    1584             :   // Protect against exponential runtime and stack overflow.
    1585         125 :   if (Depth > 6)
    1586             :     return false;
    1587         125 :   if (Opcode == ISD::AND || Opcode == ISD::OR) {
    1588         108 :     SDValue O0 = Val->getOperand(0);
    1589         108 :     SDValue O1 = Val->getOperand(1);
    1590             :     bool CanNegateL;
    1591          54 :     if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
    1592             :       return false;
    1593             :     bool CanNegateR;
    1594          34 :     if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
    1595             :       return false;
    1596             : 
    1597          34 :     if (Opcode == ISD::OR) {
    1598             :       // For an OR expression we need to be able to negate at least one side or
    1599             :       // we cannot do the transformation at all.
    1600          21 :       if (!CanNegateL && !CanNegateR)
    1601             :         return false;
    1602             :       // We can however change a (not (or x y)) to (and (not x) (not y)) if we
    1603             :       // can negate the x and y subtrees.
    1604          20 :       CanNegate = CanNegateL && CanNegateR;
    1605             :     } else {
    1606             :       // If the operands are OR expressions then we finally need to negate their
    1607             :       // outputs, we can only do that for the operand with emitted last by
    1608             :       // negating OutCC, not for both operands.
    1609          13 :       bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
    1610          13 :       bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
    1611          13 :       if (NeedsNegOutL && NeedsNegOutR)
    1612             :         return false;
    1613             :       // We cannot negate an AND operation (it would become an OR),
    1614          12 :       CanNegate = false;
    1615             :     }
    1616             :     return true;
    1617             :   }
    1618             :   return false;
    1619             : }
    1620             : 
    1621             : /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
    1622             : /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
    1623             : /// Tries to transform the given i1 producing node @p Val to a series compare
    1624             : /// and conditional compare operations. @returns an NZCV flags producing node
    1625             : /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
    1626             : /// transformation was not possible.
    1627             : /// On recursive invocations @p PushNegate may be set to true to have negation
    1628             : /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
    1629             : /// for the comparisons in the current subtree; @p Depth limits the search
    1630             : /// depth to avoid stack overflow.
    1631          75 : static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
    1632             :     AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
    1633             :     AArch64CC::CondCode Predicate) {
    1634             :   // We're at a tree leaf, produce a conditional comparison operation.
    1635         150 :   unsigned Opcode = Val->getOpcode();
    1636          75 :   if (Opcode == ISD::SETCC) {
    1637          96 :     SDValue LHS = Val->getOperand(0);
    1638          96 :     SDValue RHS = Val->getOperand(1);
    1639         144 :     ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
    1640          96 :     bool isInteger = LHS.getValueType().isInteger();
    1641          48 :     if (Negate)
    1642          17 :       CC = getSetCCInverse(CC, isInteger);
    1643          96 :     SDLoc DL(Val);
    1644             :     // Determine OutCC and handle FP special case.
    1645          48 :     if (isInteger) {
    1646          20 :       OutCC = changeIntCCToAArch64CC(CC);
    1647             :     } else {
    1648             :       assert(LHS.getValueType().isFloatingPoint());
    1649             :       AArch64CC::CondCode ExtraCC;
    1650          28 :       changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
    1651             :       // Some floating point conditions can't be tested with a single condition
    1652             :       // code. Construct an additional comparison in this case.
    1653          28 :       if (ExtraCC != AArch64CC::AL) {
    1654          11 :         SDValue ExtraCmp;
    1655          11 :         if (!CCOp.getNode())
    1656           4 :           ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
    1657             :         else
    1658           7 :           ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
    1659             :                                                ExtraCC, DL, DAG);
    1660          11 :         CCOp = ExtraCmp;
    1661          11 :         Predicate = ExtraCC;
    1662             :       }
    1663             :     }
    1664             : 
    1665             :     // Produce a normal comparison if we are first in the chain
    1666          48 :     if (!CCOp)
    1667          17 :       return emitComparison(LHS, RHS, CC, DL, DAG);
    1668             :     // Otherwise produce a ccmp.
    1669             :     return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
    1670          31 :                                      DAG);
    1671             :   }
    1672             :   assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
    1673             :          "Valid conjunction/disjunction tree");
    1674             : 
    1675             :   // Check if both sides can be transformed.
    1676          54 :   SDValue LHS = Val->getOperand(0);
    1677          54 :   SDValue RHS = Val->getOperand(1);
    1678             : 
    1679             :   // In case of an OR we need to negate our operands and the result.
    1680             :   // (A v B) <=> not(not(A) ^ not(B))
    1681          27 :   bool NegateOpsAndResult = Opcode == ISD::OR;
    1682             :   // We can negate the results of all previous operations by inverting the
    1683             :   // predicate flags giving us a free negation for one side. The other side
    1684             :   // must be negatable by itself.
    1685          27 :   if (NegateOpsAndResult) {
    1686             :     // See which side we can negate.
    1687             :     bool CanNegateL;
    1688          17 :     bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
    1689             :     assert(isValidL && "Valid conjunction/disjunction tree");
    1690             :     (void)isValidL;
    1691             : 
    1692             : #ifndef NDEBUG
    1693             :     bool CanNegateR;
    1694             :     bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
    1695             :     assert(isValidR && "Valid conjunction/disjunction tree");
    1696             :     assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
    1697             : #endif
    1698             : 
    1699             :     // Order the side which we cannot negate to RHS so we can emit it first.
    1700          17 :     if (!CanNegateL)
    1701             :       std::swap(LHS, RHS);
    1702             :   } else {
    1703          20 :     bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
    1704             :     assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
    1705             :            "Valid conjunction/disjunction tree");
    1706             :     // Order the side where we need to negate the output flags to RHS so it
    1707             :     // gets emitted first.
    1708          10 :     if (NeedsNegOutL)
    1709             :       std::swap(LHS, RHS);
    1710             :   }
    1711             : 
    1712             :   // Emit RHS. If we want to negate the tree we only need to push a negate
    1713             :   // through if we are already in a PushNegate case, otherwise we can negate
    1714             :   // the "flags to test" afterwards.
    1715             :   AArch64CC::CondCode RHSCC;
    1716             :   SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
    1717          27 :                                                    CCOp, Predicate);
    1718          27 :   if (NegateOpsAndResult && !Negate)
    1719          32 :     RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
    1720             :   // Emit LHS. We may need to negate it.
    1721             :   SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
    1722             :                                                    NegateOpsAndResult, CmpR,
    1723          27 :                                                    RHSCC);
    1724             :   // If we transformed an OR to and AND then we have to negate the result
    1725             :   // (or absorb the Negate parameter).
    1726          27 :   if (NegateOpsAndResult && !Negate)
    1727          32 :     OutCC = AArch64CC::getInvertedCondCode(OutCC);
    1728          27 :   return CmpL;
    1729             : }
    1730             : 
    1731             : /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
    1732             : /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
    1733             : /// \see emitConjunctionDisjunctionTreeRec().
    1734         113 : static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
    1735             :                                               AArch64CC::CondCode &OutCC) {
    1736             :   bool CanNegate;
    1737         113 :   if (!isConjunctionDisjunctionTree(Val, CanNegate))
    1738          92 :     return SDValue();
    1739             : 
    1740             :   return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
    1741          21 :                                            AArch64CC::AL);
    1742             : }
    1743             : 
    1744             : /// @}
    1745             : 
    1746         681 : static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
    1747             :                              SDValue &AArch64cc, SelectionDAG &DAG,
    1748             :                              const SDLoc &dl) {
    1749        1083 :   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
    1750         804 :     EVT VT = RHS.getValueType();
    1751         402 :     uint64_t C = RHSC->getZExtValue();
    1752          30 :     if (!isLegalArithImmed(C)) {
    1753             :       // Constant does not fit, try adjusting it by one?
    1754          30 :       switch (CC) {
    1755             :       default:
    1756             :         break;
    1757           4 :       case ISD::SETLT:
    1758             :       case ISD::SETGE:
    1759           8 :         if ((VT == MVT::i32 && C != 0x80000000 &&
    1760           4 :              isLegalArithImmed((uint32_t)(C - 1))) ||
    1761           4 :             (VT == MVT::i64 && C != 0x80000000ULL &&
    1762           0 :              isLegalArithImmed(C - 1ULL))) {
    1763           0 :           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
    1764           0 :           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
    1765           0 :           RHS = DAG.getConstant(C, dl, VT);
    1766             :         }
    1767             :         break;
    1768           1 :       case ISD::SETULT:
    1769             :       case ISD::SETUGE:
    1770           2 :         if ((VT == MVT::i32 && C != 0 &&
    1771           1 :              isLegalArithImmed((uint32_t)(C - 1))) ||
    1772           1 :             (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
    1773           0 :           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
    1774           0 :           C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
    1775           0 :           RHS = DAG.getConstant(C, dl, VT);
    1776             :         }
    1777             :         break;
    1778          10 :       case ISD::SETLE:
    1779             :       case ISD::SETGT:
    1780          17 :         if ((VT == MVT::i32 && C != INT32_MAX &&
    1781           7 :              isLegalArithImmed((uint32_t)(C + 1))) ||
    1782          11 :             (VT == MVT::i64 && C != INT64_MAX &&
    1783           3 :              isLegalArithImmed(C + 1ULL))) {
    1784           4 :           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
    1785           6 :           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
    1786           4 :           RHS = DAG.getConstant(C, dl, VT);
    1787             :         }
    1788             :         break;
    1789           5 :       case ISD::SETULE:
    1790             :       case ISD::SETUGT:
    1791           8 :         if ((VT == MVT::i32 && C != UINT32_MAX &&
    1792           3 :              isLegalArithImmed((uint32_t)(C + 1))) ||
    1793           7 :             (VT == MVT::i64 && C != UINT64_MAX &&
    1794           0 :              isLegalArithImmed(C + 1ULL))) {
    1795           0 :           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
    1796           0 :           C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
    1797           0 :           RHS = DAG.getConstant(C, dl, VT);
    1798             :         }
    1799             :         break;
    1800             :       }
    1801             :     }
    1802             :   }
    1803         681 :   SDValue Cmp;
    1804             :   AArch64CC::CondCode AArch64CC;
    1805         681 :   if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
    1806         204 :     const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
    1807             : 
    1808             :     // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
    1809             :     // For the i8 operand, the largest immediate is 255, so this can be easily
    1810             :     // encoded in the compare instruction. For the i16 operand, however, the
    1811             :     // largest immediate cannot be encoded in the compare.
    1812             :     // Therefore, use a sign extending load and cmn to avoid materializing the
    1813             :     // -1 constant. For example,
    1814             :     // movz w1, #65535
    1815             :     // ldrh w0, [x0, #0]
    1816             :     // cmp w0, w1
    1817             :     // >
    1818             :     // ldrsh w0, [x0, #0]
    1819             :     // cmn w0, #1
    1820             :     // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
    1821             :     // if and only if (sext LHS) == (sext RHS). The checks are in place to
    1822             :     // ensure both the LHS and RHS are truly zero extended and to make sure the
    1823             :     // transformation is profitable.
    1824         412 :     if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
    1825          18 :         cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
    1826         218 :         cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
    1827           2 :         LHS.getNode()->hasNUsesOfValue(1, 0)) {
    1828           4 :       int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
    1829           2 :       if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
    1830             :         SDValue SExt =
    1831             :             DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
    1832           6 :                         DAG.getValueType(MVT::i16));
    1833           2 :         Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
    1834             :                                                    RHS.getValueType()),
    1835           4 :                              CC, dl, DAG);
    1836           2 :         AArch64CC = changeIntCCToAArch64CC(CC);
    1837             :       }
    1838             :     }
    1839             : 
    1840         520 :     if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
    1841         113 :       if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
    1842          21 :         if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
    1843           2 :           AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
    1844             :       }
    1845             :     }
    1846             :   }
    1847             : 
    1848         681 :   if (!Cmp) {
    1849         658 :     Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
    1850         658 :     AArch64CC = changeIntCCToAArch64CC(CC);
    1851             :   }
    1852         681 :   AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
    1853         681 :   return Cmp;
    1854             : }
    1855             : 
    1856             : static std::pair<SDValue, SDValue>
    1857          50 : getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
    1858             :   assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
    1859             :          "Unsupported value type");
    1860          50 :   SDValue Value, Overflow;
    1861         100 :   SDLoc DL(Op);
    1862         100 :   SDValue LHS = Op.getOperand(0);
    1863         100 :   SDValue RHS = Op.getOperand(1);
    1864          50 :   unsigned Opc = 0;
    1865         100 :   switch (Op.getOpcode()) {
    1866           0 :   default:
    1867           0 :     llvm_unreachable("Unknown overflow instruction!");
    1868          15 :   case ISD::SADDO:
    1869          15 :     Opc = AArch64ISD::ADDS;
    1870          15 :     CC = AArch64CC::VS;
    1871             :     break;
    1872           9 :   case ISD::UADDO:
    1873           9 :     Opc = AArch64ISD::ADDS;
    1874           9 :     CC = AArch64CC::HS;
    1875             :     break;
    1876           7 :   case ISD::SSUBO:
    1877           7 :     Opc = AArch64ISD::SUBS;
    1878           7 :     CC = AArch64CC::VS;
    1879             :     break;
    1880           6 :   case ISD::USUBO:
    1881           6 :     Opc = AArch64ISD::SUBS;
    1882           6 :     CC = AArch64CC::LO;
    1883             :     break;
    1884             :   // Multiply needs a little bit extra work.
    1885          13 :   case ISD::SMULO:
    1886             :   case ISD::UMULO: {
    1887          13 :     CC = AArch64CC::NE;
    1888          26 :     bool IsSigned = Op.getOpcode() == ISD::SMULO;
    1889          39 :     if (Op.getValueType() == MVT::i32) {
    1890           6 :       unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
    1891             :       // For a 32 bit multiply with overflow check we want the instruction
    1892             :       // selector to generate a widening multiply (SMADDL/UMADDL). For that we
    1893             :       // need to generate the following pattern:
    1894             :       // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
    1895          12 :       LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
    1896          12 :       RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
    1897          12 :       SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
    1898             :       SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
    1899          18 :                                 DAG.getConstant(0, DL, MVT::i64));
    1900             :       // On AArch64 the upper 32 bits are always zero extended for a 32 bit
    1901             :       // operation. We need to clear out the upper 32 bits, because we used a
    1902             :       // widening multiply that wrote all 64 bits. In the end this should be a
    1903             :       // noop.
    1904          12 :       Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
    1905           6 :       if (IsSigned) {
    1906             :         // The signed overflow check requires more than just a simple check for
    1907             :         // any bit set in the upper 32 bits of the result. These bits could be
    1908             :         // just the sign bits of a negative number. To perform the overflow
    1909             :         // check we have to arithmetic shift right the 32nd bit of the result by
    1910             :         // 31 bits. Then we compare the result to the upper 32 bits.
    1911             :         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
    1912           9 :                                         DAG.getConstant(32, DL, MVT::i64));
    1913           6 :         UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
    1914             :         SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
    1915           9 :                                         DAG.getConstant(31, DL, MVT::i64));
    1916             :         // It is important that LowerBits is last, otherwise the arithmetic
    1917             :         // shift will not be folded into the compare (SUBS).
    1918           6 :         SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
    1919           6 :         Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
    1920           6 :                        .getValue(1);
    1921             :       } else {
    1922             :         // The overflow check for unsigned multiply is easy. We only need to
    1923             :         // check if any of the upper 32 bits are set. This can be done with a
    1924             :         // CMP (shifted register). For that we need to generate the following
    1925             :         // pattern:
    1926             :         // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
    1927             :         SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
    1928           9 :                                         DAG.getConstant(32, DL, MVT::i64));
    1929           6 :         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
    1930           3 :         Overflow =
    1931           6 :             DAG.getNode(AArch64ISD::SUBS, DL, VTs,
    1932           3 :                         DAG.getConstant(0, DL, MVT::i64),
    1933          12 :                         UpperBits).getValue(1);
    1934             :       }
    1935             :       break;
    1936             :     }
    1937             :     assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
    1938             :     // For the 64 bit multiply
    1939          14 :     Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
    1940           7 :     if (IsSigned) {
    1941           6 :       SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
    1942             :       SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
    1943           9 :                                       DAG.getConstant(63, DL, MVT::i64));
    1944             :       // It is important that LowerBits is last, otherwise the arithmetic
    1945             :       // shift will not be folded into the compare (SUBS).
    1946           6 :       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
    1947           6 :       Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
    1948           6 :                      .getValue(1);
    1949             :     } else {
    1950           8 :       SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
    1951           8 :       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
    1952           4 :       Overflow =
    1953           8 :           DAG.getNode(AArch64ISD::SUBS, DL, VTs,
    1954           4 :                       DAG.getConstant(0, DL, MVT::i64),
    1955          16 :                       UpperBits).getValue(1);
    1956             :     }
    1957             :     break;
    1958             :   }
    1959             :   } // switch (...)
    1960             : 
    1961             :   if (Opc) {
    1962          74 :     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
    1963             : 
    1964             :     // Emit the AArch64 operation with overflow check.
    1965          37 :     Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
    1966          74 :     Overflow = Value.getValue(1);
    1967             :   }
    1968         100 :   return std::make_pair(Value, Overflow);
    1969             : }
    1970             : 
    1971          91 : SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
    1972             :                                              RTLIB::Libcall Call) const {
    1973         364 :   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
    1974         546 :   return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
    1975             : }
    1976             : 
    1977         215 : static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
    1978         430 :   SDValue Sel = Op.getOperand(0);
    1979         430 :   SDValue Other = Op.getOperand(1);
    1980             : 
    1981             :   // If neither operand is a SELECT_CC, give up.
    1982         430 :   if (Sel.getOpcode() != ISD::SELECT_CC)
    1983             :     std::swap(Sel, Other);
    1984         430 :   if (Sel.getOpcode() != ISD::SELECT_CC)
    1985         214 :     return Op;
    1986             : 
    1987             :   // The folding we want to perform is:
    1988             :   // (xor x, (select_cc a, b, cc, 0, -1) )
    1989             :   //   -->
    1990             :   // (csel x, (xor x, -1), cc ...)
    1991             :   //
    1992             :   // The latter will get matched to a CSINV instruction.
    1993             : 
    1994           3 :   ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
    1995           2 :   SDValue LHS = Sel.getOperand(0);
    1996           2 :   SDValue RHS = Sel.getOperand(1);
    1997           2 :   SDValue TVal = Sel.getOperand(2);
    1998           2 :   SDValue FVal = Sel.getOperand(3);
    1999           1 :   SDLoc dl(Sel);
    2000             : 
    2001             :   // FIXME: This could be generalized to non-integer comparisons.
    2002           2 :   if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
    2003           0 :     return Op;
    2004             : 
    2005           1 :   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
    2006           1 :   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
    2007             : 
    2008             :   // The values aren't constants, this isn't the pattern we're looking for.
    2009           1 :   if (!CFVal || !CTVal)
    2010           0 :     return Op;
    2011             : 
    2012             :   // We can commute the SELECT_CC by inverting the condition.  This
    2013             :   // might be needed to make this fit into a CSINV pattern.
    2014           3 :   if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
    2015           1 :     std::swap(TVal, FVal);
    2016           1 :     std::swap(CTVal, CFVal);
    2017           1 :     CC = ISD::getSetCCInverse(CC, true);
    2018             :   }
    2019             : 
    2020             :   // If the constants line up, perform the transform!
    2021           3 :   if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
    2022           1 :     SDValue CCVal;
    2023           1 :     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
    2024             : 
    2025           1 :     FVal = Other;
    2026           1 :     TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
    2027           3 :                        DAG.getConstant(-1ULL, dl, Other.getValueType()));
    2028             : 
    2029             :     return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
    2030           2 :                        CCVal, Cmp);
    2031             :   }
    2032             : 
    2033           0 :   return Op;
    2034             : }
    2035             : 
    2036          42 : static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
    2037          84 :   EVT VT = Op.getValueType();
    2038             : 
    2039             :   // Let legalize expand this if it isn't a legal type yet.
    2040          84 :   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
    2041           0 :     return SDValue();
    2042             : 
    2043          42 :   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
    2044             : 
    2045             :   unsigned Opc;
    2046          42 :   bool ExtraOp = false;
    2047          84 :   switch (Op.getOpcode()) {
    2048           0 :   default:
    2049           0 :     llvm_unreachable("Invalid code");
    2050             :   case ISD::ADDC:
    2051             :     Opc = AArch64ISD::ADDS;
    2052             :     break;
    2053           3 :   case ISD::SUBC:
    2054           3 :     Opc = AArch64ISD::SUBS;
    2055             :     break;
    2056          20 :   case ISD::ADDE:
    2057          20 :     Opc = AArch64ISD::ADCS;
    2058          20 :     ExtraOp = true;
    2059             :     break;
    2060           3 :   case ISD::SUBE:
    2061           3 :     Opc = AArch64ISD::SBCS;
    2062           3 :     ExtraOp = true;
    2063             :     break;
    2064             :   }
    2065             : 
    2066          42 :   if (!ExtraOp)
    2067          95 :     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
    2068         115 :   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
    2069          69 :                      Op.getOperand(2));
    2070             : }
    2071             : 
    2072          23 : static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
    2073             :   // Let legalize expand this if it isn't a legal type yet.
    2074          69 :   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
    2075           0 :     return SDValue();
    2076             : 
    2077          23 :   SDLoc dl(Op);
    2078             :   AArch64CC::CondCode CC;
    2079             :   // The actual operation that sets the overflow or carry flag.
    2080             :   SDValue Value, Overflow;
    2081          69 :   std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
    2082             : 
    2083             :   // We use 0 and 1 as false and true values.
    2084          23 :   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
    2085          23 :   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
    2086             : 
    2087             :   // We use an inverted condition, because the conditional select is inverted
    2088             :   // too. This will allow it to be selected to a single instruction:
    2089             :   // CSINC Wd, WZR, WZR, invert(cond).
    2090          46 :   SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
    2091          23 :   Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
    2092          46 :                          CCVal, Overflow);
    2093             : 
    2094          46 :   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
    2095          23 :   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
    2096             : }
    2097             : 
    2098             : // Prefetch operands are:
    2099             : // 1: Address to prefetch
    2100             : // 2: bool isWrite
    2101             : // 3: int locality (0 = no locality ... 3 = extreme locality)
    2102             : // 4: bool isDataCache
    2103          24 : static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
    2104          48 :   SDLoc DL(Op);
    2105          96 :   unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
    2106          96 :   unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
    2107          96 :   unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
    2108             : 
    2109          24 :   bool IsStream = !Locality;
    2110             :   // When the locality number is set
    2111          24 :   if (Locality) {
    2112             :     // The front-end should have filtered out the out-of-range values
    2113             :     assert(Locality <= 3 && "Prefetch locality out-of-range");
    2114             :     // The locality degree is the opposite of the cache speed.
    2115             :     // Put the number the other way around.
    2116             :     // The encoding starts at 0 for level 1
    2117          18 :     Locality = 3 - Locality;
    2118             :   }
    2119             : 
    2120             :   // built the mask value encoding the expected behavior.
    2121          72 :   unsigned PrfOp = (IsWrite << 4) |     // Load/Store bit
    2122          48 :                    (!IsData << 3) |     // IsDataCache bit
    2123          24 :                    (Locality << 1) |    // Cache level bits
    2124          24 :                    (unsigned)IsStream;  // Stream bit
    2125          48 :   return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
    2126         120 :                      DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
    2127             : }
    2128             : 
    2129           2 : SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
    2130             :                                               SelectionDAG &DAG) const {
    2131             :   assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
    2132             : 
    2133             :   RTLIB::Libcall LC;
    2134           8 :   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
    2135             : 
    2136           2 :   return LowerF128Call(Op, DAG, LC);
    2137             : }
    2138             : 
    2139          36 : SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
    2140             :                                              SelectionDAG &DAG) const {
    2141         108 :   if (Op.getOperand(0).getValueType() != MVT::f128) {
    2142             :     // It's legal except when f128 is involved
    2143          31 :     return Op;
    2144             :   }
    2145             : 
    2146             :   RTLIB::Libcall LC;
    2147          20 :   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
    2148             : 
    2149             :   // FP_ROUND node has a second operand indicating whether it is known to be
    2150             :   // precise. That doesn't take part in the LibCall so we can't directly use
    2151             :   // LowerF128Call.
    2152          10 :   SDValue SrcVal = Op.getOperand(0);
    2153          10 :   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
    2154          30 :                      SDLoc(Op)).first;
    2155             : }
    2156             : 
    2157         216 : static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
    2158             :   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
    2159             :   // Any additional optimization in this function should be recorded
    2160             :   // in the cost tables.
    2161         648 :   EVT InVT = Op.getOperand(0).getValueType();
    2162         432 :   EVT VT = Op.getValueType();
    2163         216 :   unsigned NumElts = InVT.getVectorNumElements();
    2164             : 
    2165             :   // f16 vectors are promoted to f32 before a conversion.
    2166         432 :   if (InVT.getVectorElementType() == MVT::f16) {
    2167          12 :     MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
    2168          24 :     SDLoc dl(Op);
    2169             :     return DAG.getNode(
    2170             :         Op.getOpcode(), dl, Op.getValueType(),
    2171          72 :         DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
    2172             :   }
    2173             : 
    2174         204 :   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
    2175          64 :     SDLoc dl(Op);
    2176             :     SDValue Cv =
    2177             :         DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
    2178          96 :                     Op.getOperand(0));
    2179          32 :     return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
    2180             :   }
    2181             : 
    2182         172 :   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
    2183           6 :     SDLoc dl(Op);
    2184             :     MVT ExtVT =
    2185             :         MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
    2186           9 :                          VT.getVectorNumElements());
    2187           9 :     SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
    2188           6 :     return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
    2189             :   }
    2190             : 
    2191             :   // Type changing conversions are illegal.
    2192         169 :   return Op;
    2193             : }
    2194             : 
    2195         429 : SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
    2196             :                                               SelectionDAG &DAG) const {
    2197        1716 :   if (Op.getOperand(0).getValueType().isVector())
    2198         216 :     return LowerVectorFP_TO_INT(Op, DAG);
    2199             : 
    2200             :   // f16 conversions are promoted to f32 when full fp16 is not supported.
    2201         654 :   if (Op.getOperand(0).getValueType() == MVT::f16 &&
    2202          15 :       !Subtarget->hasFullFP16()) {
    2203          14 :     SDLoc dl(Op);
    2204             :     return DAG.getNode(
    2205             :         Op.getOpcode(), dl, Op.getValueType(),
    2206          42 :         DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
    2207             :   }
    2208             : 
    2209         618 :   if (Op.getOperand(0).getValueType() != MVT::f128) {
    2210             :     // It's legal except when f128 is involved
    2211         194 :     return Op;
    2212             :   }
    2213             : 
    2214             :   RTLIB::Libcall LC;
    2215          24 :   if (Op.getOpcode() == ISD::FP_TO_SINT)
    2216          20 :     LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
    2217             :   else
    2218          28 :     LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
    2219             : 
    2220          36 :   SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
    2221          60 :   return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
    2222             : }
    2223             : 
    2224         359 : static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
    2225             :   // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
    2226             :   // Any additional optimization in this function should be recorded
    2227             :   // in the cost tables.
    2228         718 :   EVT VT = Op.getValueType();
    2229         718 :   SDLoc dl(Op);
    2230         718 :   SDValue In = Op.getOperand(0);
    2231         718 :   EVT InVT = In.getValueType();
    2232             : 
    2233         359 :   if (VT.getSizeInBits() < InVT.getSizeInBits()) {
    2234             :     MVT CastVT =
    2235             :         MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
    2236         210 :                          InVT.getVectorNumElements());
    2237         210 :     In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
    2238          70 :     return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
    2239             :   }
    2240             : 
    2241         289 :   if (VT.getSizeInBits() > InVT.getSizeInBits()) {
    2242             :     unsigned CastOpc =
    2243          18 :         Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
    2244           9 :     EVT CastVT = VT.changeVectorElementTypeToInteger();
    2245           9 :     In = DAG.getNode(CastOpc, dl, CastVT, In);
    2246          18 :     return DAG.getNode(Op.getOpcode(), dl, VT, In);
    2247             :   }
    2248             : 
    2249         280 :   return Op;
    2250             : }
    2251             : 
    2252         643 : SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
    2253             :                                             SelectionDAG &DAG) const {
    2254        1929 :   if (Op.getValueType().isVector())
    2255         359 :     return LowerVectorINT_TO_FP(Op, DAG);
    2256             : 
    2257             :   // f16 conversions are promoted to f32 when full fp16 is not supported.
    2258         596 :   if (Op.getValueType() == MVT::f16 &&
    2259          28 :       !Subtarget->hasFullFP16()) {
    2260          32 :     SDLoc dl(Op);
    2261             :     return DAG.getNode(
    2262             :         ISD::FP_ROUND, dl, MVT::f16,
    2263          48 :         DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
    2264          80 :         DAG.getIntPtrConstant(0, dl));
    2265             :   }
    2266             : 
    2267             :   // i128 conversions are libcalls.
    2268        1072 :   if (Op.getOperand(0).getValueType() == MVT::i128)
    2269           6 :     return SDValue();
    2270             : 
    2271             :   // Other conversions are legal, unless it's to the completely software-based
    2272             :   // fp128.
    2273         524 :   if (Op.getValueType() != MVT::f128)
    2274         256 :     return Op;
    2275             : 
    2276             :   RTLIB::Libcall LC;
    2277          12 :   if (Op.getOpcode() == ISD::SINT_TO_FP)
    2278           8 :     LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
    2279             :   else
    2280          16 :     LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
    2281             : 
    2282           6 :   return LowerF128Call(Op, DAG, LC);
    2283             : }
    2284             : 
    2285           2 : SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
    2286             :                                             SelectionDAG &DAG) const {
    2287             :   // For iOS, we want to call an alternative entry point: __sincos_stret,
    2288             :   // which returns the values in two S / D registers.
    2289           4 :   SDLoc dl(Op);
    2290           4 :   SDValue Arg = Op.getOperand(0);
    2291           4 :   EVT ArgVT = Arg.getValueType();
    2292           2 :   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
    2293             : 
    2294           4 :   ArgListTy Args;
    2295           2 :   ArgListEntry Entry;
    2296             : 
    2297           2 :   Entry.Node = Arg;
    2298           2 :   Entry.Ty = ArgTy;
    2299             :   Entry.IsSExt = false;
    2300             :   Entry.IsZExt = false;
    2301           2 :   Args.push_back(Entry);
    2302             : 
    2303             :   const char *LibcallName =
    2304           4 :       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
    2305             :   SDValue Callee =
    2306           8 :       DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
    2307             : 
    2308           2 :   StructType *RetTy = StructType::get(ArgTy, ArgTy);
    2309           4 :   TargetLowering::CallLoweringInfo CLI(DAG);
    2310           2 :   CLI.setDebugLoc(dl)
    2311           4 :       .setChain(DAG.getEntryNode())
    2312           2 :       .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
    2313             : 
    2314           2 :   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
    2315           4 :   return CallResult.first;
    2316             : }
    2317             : 
    2318           8 : static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
    2319          16 :   if (Op.getValueType() != MVT::f16)
    2320           0 :     return SDValue();
    2321             : 
    2322             :   assert(Op.getOperand(0).getValueType() == MVT::i16);
    2323           8 :   SDLoc DL(Op);
    2324             : 
    2325          24 :   Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
    2326          16 :   Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
    2327           8 :   return SDValue(
    2328          24 :       DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
    2329          16 :                          DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
    2330           8 :       0);
    2331             : }
    2332             : 
    2333           0 : static EVT getExtensionTo64Bits(const EVT &OrigVT) {
    2334           0 :   if (OrigVT.getSizeInBits() >= 64)
    2335           0 :     return OrigVT;
    2336             : 
    2337             :   assert(OrigVT.isSimple() && "Expecting a simple value type");
    2338             : 
    2339           0 :   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
    2340           0 :   switch (OrigSimpleTy) {
    2341           0 :   default: llvm_unreachable("Unexpected Vector Type");
    2342           0 :   case MVT::v2i8:
    2343             :   case MVT::v2i16:
    2344           0 :      return MVT::v2i32;
    2345           0 :   case MVT::v4i8:
    2346           0 :     return  MVT::v4i16;
    2347             :   }
    2348             : }
    2349             : 
    2350          45 : static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
    2351             :                                                  const EVT &OrigTy,
    2352             :                                                  const EVT &ExtTy,
    2353             :                                                  unsigned ExtOpcode) {
    2354             :   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
    2355             :   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
    2356             :   // 64-bits we need to insert a new extension so that it will be 64-bits.
    2357             :   assert(ExtTy.is128BitVector() && "Unexpected extension size");
    2358          45 :   if (OrigTy.getSizeInBits() >= 64)
    2359          45 :     return N;
    2360             : 
    2361             :   // Must extend size to at least 64 bits to be used as an operand for VMULL.
    2362           0 :   EVT NewVT = getExtensionTo64Bits(OrigTy);
    2363             : 
    2364           0 :   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
    2365             : }
    2366             : 
    2367        1194 : static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
    2368             :                                    bool isSigned) {
    2369        2388 :   EVT VT = N->getValueType(0);
    2370             : 
    2371        1194 :   if (N->getOpcode() != ISD::BUILD_VECTOR)
    2372             :     return false;
    2373             : 
    2374         276 :   for (const SDValue &Elt : N->op_values()) {
    2375          72 :     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
    2376          72 :       unsigned EltSize = VT.getScalarSizeInBits();
    2377          72 :       unsigned HalfSize = EltSize / 2;
    2378          72 :       if (isSigned) {
    2379          36 :         if (!isIntN(HalfSize, C->getSExtValue()))
    2380             :           return false;
    2381             :       } else {
    2382          36 :         if (!isUIntN(HalfSize, C->getZExtValue()))
    2383             :           return false;
    2384             :       }
    2385          58 :       continue;
    2386             :     }
    2387             :     return false;
    2388             :   }
    2389             : 
    2390             :   return true;
    2391             : }
    2392             : 
    2393          51 : static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
    2394         102 :   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
    2395          90 :     return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
    2396         180 :                                              N->getOperand(0)->getValueType(0),
    2397          90 :                                              N->getValueType(0),
    2398          90 :                                              N->getOpcode());
    2399             : 
    2400             :   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
    2401          12 :   EVT VT = N->getValueType(0);
    2402           6 :   SDLoc dl(N);
    2403           6 :   unsigned EltSize = VT.getScalarSizeInBits() / 2;
    2404           6 :   unsigned NumElts = VT.getVectorNumElements();
    2405           6 :   MVT TruncVT = MVT::getIntegerVT(EltSize);
    2406          12 :   SmallVector<SDValue, 8> Ops;
    2407          34 :   for (unsigned i = 0; i != NumElts; ++i) {
    2408          84 :     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
    2409          28 :     const APInt &CInt = C->getAPIntValue();
    2410             :     // Element types smaller than 32 bits are not legal, so use i32 elements.
    2411             :     // The values are implicitly truncated so sext vs. zext doesn't matter.
    2412          56 :     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
    2413             :   }
    2414          12 :   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
    2415             : }
    2416             : 
    2417             : static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
    2418        1255 :   return N->getOpcode() == ISD::SIGN_EXTEND ||
    2419         611 :          isExtendedBUILD_VECTOR(N, DAG, true);
    2420             : }
    2421             : 
    2422             : static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
    2423        1198 :   return N->getOpcode() == ISD::ZERO_EXTEND ||
    2424         583 :          isExtendedBUILD_VECTOR(N, DAG, false);
    2425             : }
    2426             : 
    2427           0 : static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
    2428           0 :   unsigned Opcode = N->getOpcode();
    2429           0 :   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
    2430           0 :     SDNode *N0 = N->getOperand(0).getNode();
    2431           0 :     SDNode *N1 = N->getOperand(1).getNode();
    2432           0 :     return N0->hasOneUse() && N1->hasOneUse() &&
    2433             :       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
    2434             :   }
    2435             :   return false;
    2436             : }
    2437             : 
    2438           3 : static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
    2439           6 :   unsigned Opcode = N->getOpcode();
    2440           3 :   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
    2441           2 :     SDNode *N0 = N->getOperand(0).getNode();
    2442           2 :     SDNode *N1 = N->getOperand(1).getNode();
    2443           2 :     return N0->hasOneUse() && N1->hasOneUse() &&
    2444             :       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
    2445             :   }
    2446             :   return false;
    2447             : }
    2448             : 
    2449         291 : static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
    2450             :   // Multiplications are only custom-lowered for 128-bit vectors so that
    2451             :   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
    2452         582 :   EVT VT = Op.getValueType();
    2453             :   assert(VT.is128BitVector() && VT.isInteger() &&
    2454             :          "unexpected type for custom-lowering ISD::MUL");
    2455         582 :   SDNode *N0 = Op.getOperand(0).getNode();
    2456         582 :   SDNode *N1 = Op.getOperand(1).getNode();
    2457         291 :   unsigned NewOpc = 0;
    2458         291 :   bool isMLA = false;
    2459         582 :   bool isN0SExt = isSignExtended(N0, DAG);
    2460         582 :   bool isN1SExt = isSignExtended(N1, DAG);
    2461         291 :   if (isN0SExt && isN1SExt)
    2462             :     NewOpc = AArch64ISD::SMULL;
    2463             :   else {
    2464         558 :     bool isN0ZExt = isZeroExtended(N0, DAG);
    2465         558 :     bool isN1ZExt = isZeroExtended(N1, DAG);
    2466         279 :     if (isN0ZExt && isN1ZExt)
    2467             :       NewOpc = AArch64ISD::UMULL;
    2468         267 :     else if (isN1SExt || isN1ZExt) {
    2469             :       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
    2470             :       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
    2471           3 :       if (isN1SExt && isAddSubSExt(N0, DAG)) {
    2472             :         NewOpc = AArch64ISD::SMULL;
    2473             :         isMLA = true;
    2474           3 :       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
    2475             :         NewOpc =  AArch64ISD::UMULL;
    2476             :         isMLA = true;
    2477           2 :       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
    2478             :         std::swap(N0, N1);
    2479             :         NewOpc =  AArch64ISD::UMULL;
    2480             :         isMLA = true;
    2481             :       }
    2482             :     }
    2483             : 
    2484         279 :     if (!NewOpc) {
    2485         532 :       if (VT == MVT::v2i64)
    2486             :         // Fall through to expand this.  It is not legal.
    2487           2 :         return SDValue();
    2488             :       else
    2489             :         // Other vector multiplications are legal.
    2490         264 :         return Op;
    2491             :     }
    2492             :   }
    2493             : 
    2494             :   // Legalize to a S/UMULL instruction
    2495          25 :   SDLoc DL(Op);
    2496          25 :   SDValue Op0;
    2497          25 :   SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
    2498          25 :   if (!isMLA) {
    2499          24 :     Op0 = skipExtensionForVectorMULL(N0, DAG);
    2500             :     assert(Op0.getValueType().is64BitVector() &&
    2501             :            Op1.getValueType().is64BitVector() &&
    2502             :            "unexpected types for extended operands to VMULL");
    2503          24 :     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
    2504             :   }
    2505             :   // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
    2506             :   // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
    2507             :   // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
    2508           2 :   SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
    2509           2 :   SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
    2510           2 :   EVT Op1VT = Op1.getValueType();
    2511             :   return DAG.getNode(N0->getOpcode(), DL, VT,
    2512             :                      DAG.getNode(NewOpc, DL, VT,
    2513             :                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
    2514             :                      DAG.getNode(NewOpc, DL, VT,
    2515           6 :                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
    2516             : }
    2517             : 
    2518        4791 : SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
    2519             :                                                      SelectionDAG &DAG) const {
    2520       19164 :   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
    2521        9582 :   SDLoc dl(Op);
    2522        4791 :   switch (IntNo) {
    2523        4704 :   default: return SDValue();    // Don't custom lower most intrinsics.
    2524           6 :   case Intrinsic::thread_pointer: {
    2525          24 :     EVT PtrVT = getPointerTy(DAG.getDataLayout());
    2526           6 :     return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
    2527             :   }
    2528           8 :   case Intrinsic::aarch64_neon_abs:
    2529             :     return DAG.getNode(ISD::ABS, dl, Op.getValueType(),
    2530          24 :                        Op.getOperand(1));
    2531          19 :   case Intrinsic::aarch64_neon_smax:
    2532             :     return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
    2533          76 :                        Op.getOperand(1), Op.getOperand(2));
    2534          18 :   case Intrinsic::aarch64_neon_umax:
    2535             :     return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
    2536          72 :                        Op.getOperand(1), Op.getOperand(2));
    2537          18 :   case Intrinsic::aarch64_neon_smin:
    2538             :     return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
    2539          72 :                        Op.getOperand(1), Op.getOperand(2));
    2540          18 :   case Intrinsic::aarch64_neon_umin:
    2541             :     return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
    2542          72 :                        Op.getOperand(1), Op.getOperand(2));
    2543             :   }
    2544             : }
    2545             : 
    2546       22712 : SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
    2547             :                                               SelectionDAG &DAG) const {
    2548             :   DEBUG(dbgs() << "Custom lowering: ");
    2549             :   DEBUG(Op.dump());
    2550             : 
    2551       45424 :   switch (Op.getOpcode()) {
    2552           0 :   default:
    2553           0 :     llvm_unreachable("unimplemented operand");
    2554             :     return SDValue();
    2555           8 :   case ISD::BITCAST:
    2556           8 :     return LowerBITCAST(Op, DAG);
    2557        2019 :   case ISD::GlobalAddress:
    2558        2019 :     return LowerGlobalAddress(Op, DAG);
    2559          78 :   case ISD::GlobalTLSAddress:
    2560          78 :     return LowerGlobalTLSAddress(Op, DAG);
    2561         615 :   case ISD::SETCC:
    2562         615 :     return LowerSETCC(Op, DAG);
    2563         933 :   case ISD::BR_CC:
    2564         933 :     return LowerBR_CC(Op, DAG);
    2565         293 :   case ISD::SELECT:
    2566         293 :     return LowerSELECT(Op, DAG);
    2567         193 :   case ISD::SELECT_CC:
    2568         193 :     return LowerSELECT_CC(Op, DAG);
    2569          25 :   case ISD::JumpTable:
    2570          25 :     return LowerJumpTable(Op, DAG);
    2571         126 :   case ISD::ConstantPool:
    2572         126 :     return LowerConstantPool(Op, DAG);
    2573           6 :   case ISD::BlockAddress:
    2574           6 :     return LowerBlockAddress(Op, DAG);
    2575          25 :   case ISD::VASTART:
    2576          25 :     return LowerVASTART(Op, DAG);
    2577           2 :   case ISD::VACOPY:
    2578           2 :     return LowerVACOPY(Op, DAG);
    2579          16 :   case ISD::VAARG:
    2580          16 :     return LowerVAARG(Op, DAG);
    2581          42 :   case ISD::ADDC:
    2582             :   case ISD::ADDE:
    2583             :   case ISD::SUBC:
    2584             :   case ISD::SUBE:
    2585          42 :     return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
    2586          23 :   case ISD::SADDO:
    2587             :   case ISD::UADDO:
    2588             :   case ISD::SSUBO:
    2589             :   case ISD::USUBO:
    2590             :   case ISD::SMULO:
    2591             :   case ISD::UMULO:
    2592          23 :     return LowerXALUO(Op, DAG);
    2593          77 :   case ISD::FADD:
    2594          77 :     return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
    2595           2 :   case ISD::FSUB:
    2596           2 :     return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
    2597           3 :   case ISD::FMUL:
    2598           3 :     return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
    2599           1 :   case ISD::FDIV:
    2600           1 :     return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
    2601          36 :   case ISD::FP_ROUND:
    2602          36 :     return LowerFP_ROUND(Op, DAG);
    2603           2 :   case ISD::FP_EXTEND:
    2604           2 :     return LowerFP_EXTEND(Op, DAG);
    2605           2 :   case ISD::FRAMEADDR:
    2606           2 :     return LowerFRAMEADDR(Op, DAG);
    2607           6 :   case ISD::RETURNADDR:
    2608           6 :     return LowerRETURNADDR(Op, DAG);
    2609        1812 :   case ISD::INSERT_VECTOR_ELT:
    2610        1812 :     return LowerINSERT_VECTOR_ELT(Op, DAG);
    2611        4545 :   case ISD::EXTRACT_VECTOR_ELT:
    2612        4545 :     return LowerEXTRACT_VECTOR_ELT(Op, DAG);
    2613        1420 :   case ISD::BUILD_VECTOR:
    2614        1420 :     return LowerBUILD_VECTOR(Op, DAG);
    2615        1345 :   case ISD::VECTOR_SHUFFLE:
    2616        1345 :     return LowerVECTOR_SHUFFLE(Op, DAG);
    2617        1356 :   case ISD::EXTRACT_SUBVECTOR:
    2618        1356 :     return LowerEXTRACT_SUBVECTOR(Op, DAG);
    2619         213 :   case ISD::SRA:
    2620             :   case ISD::SRL:
    2621             :   case ISD::SHL:
    2622         213 :     return LowerVectorSRA_SRL_SHL(Op, DAG);
    2623           1 :   case ISD::SHL_PARTS:
    2624           1 :     return LowerShiftLeftParts(Op, DAG);
    2625           2 :   case ISD::SRL_PARTS:
    2626             :   case ISD::SRA_PARTS:
    2627           2 :     return LowerShiftRightParts(Op, DAG);
    2628          34 :   case ISD::CTPOP:
    2629          34 :     return LowerCTPOP(Op, DAG);
    2630          29 :   case ISD::FCOPYSIGN:
    2631          29 :     return LowerFCOPYSIGN(Op, DAG);
    2632         595 :   case ISD::AND:
    2633         595 :     return LowerVectorAND(Op, DAG);
    2634         416 :   case ISD::OR:
    2635         416 :     return LowerVectorOR(Op, DAG);
    2636         215 :   case ISD::XOR:
    2637         215 :     return LowerXOR(Op, DAG);
    2638          24 :   case ISD::PREFETCH:
    2639          24 :     return LowerPREFETCH(Op, DAG);
    2640         643 :   case ISD::SINT_TO_FP:
    2641             :   case ISD::UINT_TO_FP:
    2642         643 :     return LowerINT_TO_FP(Op, DAG);
    2643         429 :   case ISD::FP_TO_SINT:
    2644             :   case ISD::FP_TO_UINT:
    2645         429 :     return LowerFP_TO_INT(Op, DAG);
    2646           2 :   case ISD::FSINCOS:
    2647           2 :     return LowerFSINCOS(Op, DAG);
    2648         291 :   case ISD::MUL:
    2649         291 :     return LowerMUL(Op, DAG);
    2650        4791 :   case ISD::INTRINSIC_WO_CHAIN:
    2651        4791 :     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
    2652          16 :   case ISD::VECREDUCE_ADD:
    2653             :   case ISD::VECREDUCE_SMAX:
    2654             :   case ISD::VECREDUCE_SMIN:
    2655             :   case ISD::VECREDUCE_UMAX:
    2656             :   case ISD::VECREDUCE_UMIN:
    2657             :   case ISD::VECREDUCE_FMAX:
    2658             :   case ISD::VECREDUCE_FMIN:
    2659          16 :     return LowerVECREDUCE(Op, DAG);
    2660             :   }
    2661             : }
    2662             : 
    2663             : //===----------------------------------------------------------------------===//
    2664             : //                      Calling Convention Implementation
    2665             : //===----------------------------------------------------------------------===//
    2666             : 
    2667             : #include "AArch64GenCallingConv.inc"
    2668             : 
    2669             : /// Selects the correct CCAssignFn for a given CallingConvention value.
    2670       24303 : CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
    2671             :                                                      bool IsVarArg) const {
    2672       24303 :   switch (CC) {
    2673           0 :   default:
    2674           0 :     report_fatal_error("Unsupported calling convention.");
    2675             :   case CallingConv::WebKit_JS:
    2676             :     return CC_AArch64_WebKit_JS;
    2677           9 :   case CallingConv::GHC:
    2678           9 :     return CC_AArch64_GHC;
    2679       24163 :   case CallingConv::C:
    2680             :   case CallingConv::Fast:
    2681             :   case CallingConv::PreserveMost:
    2682             :   case CallingConv::CXX_FAST_TLS:
    2683             :   case CallingConv::Swift:
    2684       48326 :     if (Subtarget->isTargetWindows() && IsVarArg)
    2685             :       return CC_AArch64_Win64_VarArg;
    2686       24153 :     if (!Subtarget->isTargetDarwin())
    2687             :       return CC_AArch64_AAPCS;
    2688        6326 :     return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
    2689          25 :   case CallingConv::Win64:
    2690          25 :     return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
    2691             :   }
    2692             : }
    2693             : 
    2694             : CCAssignFn *
    2695         152 : AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
    2696             :   return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
    2697         152 :                                       : RetCC_AArch64_AAPCS;
    2698             : }
    2699             : 
    2700       10565 : SDValue AArch64TargetLowering::LowerFormalArguments(
    2701             :     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
    2702             :     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
    2703             :     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
    2704       10565 :   MachineFunction &MF = DAG.getMachineFunction();
    2705       10565 :   MachineFrameInfo &MFI = MF.getFrameInfo();
    2706       31695 :   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv());
    2707             : 
    2708             :   // Assign locations to all of the incoming arguments.
    2709       21130 :   SmallVector<CCValAssign, 16> ArgLocs;
    2710             :   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
    2711       21130 :                  *DAG.getContext());
    2712             : 
    2713             :   // At this point, Ins[].VT may already be promoted to i32. To correctly
    2714             :   // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
    2715             :   // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
    2716             :   // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
    2717             :   // we use a special version of AnalyzeFormalArguments to pass in ValVT and
    2718             :   // LocVT.
    2719       21130 :   unsigned NumArgs = Ins.size();
    2720       21130 :   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
    2721       10565 :   unsigned CurArgIdx = 0;
    2722       30677 :   for (unsigned i = 0; i != NumArgs; ++i) {
    2723       40224 :     MVT ValVT = Ins[i].VT;
    2724       40224 :     if (Ins[i].isOrigArg()) {
    2725       60318 :       std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
    2726       40212 :       CurArgIdx = Ins[i].getOrigArgIndex();
    2727             : 
    2728             :       // Get type of the original argument.
    2729             :       EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
    2730       40212 :                                   /*AllowUnknown*/ true);
    2731       20106 :       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
    2732             :       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
    2733       20106 :       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
    2734         413 :         ValVT = MVT::i8;
    2735       19693 :       else if (ActualMVT == MVT::i16)
    2736         381 :         ValVT = MVT::i16;
    2737             :     }
    2738       20112 :     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
    2739             :     bool Res =
    2740       40224 :         AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
    2741             :     assert(!Res && "Call operand has unhandled type");
    2742             :     (void)Res;
    2743             :   }
    2744             :   assert(ArgLocs.size() == Ins.size());
    2745       21130 :   SmallVector<SDValue, 16> ArgValues;
    2746       41242 :   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
    2747       40224 :     CCValAssign &VA = ArgLocs[i];
    2748             : 
    2749       60336 :     if (Ins[i].Flags.isByVal()) {
    2750             :       // Byval is used for HFAs in the PCS, but the system should work in a
    2751             :       // non-compliant manner for larger structs.
    2752          40 :       EVT PtrVT = getPointerTy(DAG.getDataLayout());
    2753          20 :       int Size = Ins[i].Flags.getByValSize();
    2754          10 :       unsigned NumRegs = (Size + 7) / 8;
    2755             : 
    2756             :       // FIXME: This works on big-endian for composite byvals, which are the common
    2757             :       // case. It should also work for fundamental types too.
    2758             :       unsigned FrameIdx =
    2759          10 :         MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
    2760          10 :       SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
    2761          10 :       InVals.push_back(FrameIdxN);
    2762             : 
    2763          10 :       continue;
    2764             :     }
    2765             : 
    2766       20102 :     if (VA.isRegLoc()) {
    2767             :       // Arguments stored in registers.
    2768       39332 :       EVT RegVT = VA.getLocVT();
    2769             : 
    2770       19666 :       SDValue ArgValue;
    2771             :       const TargetRegisterClass *RC;
    2772             : 
    2773       36449 :       if (RegVT == MVT::i32)
    2774             :         RC = &AArch64::GPR32RegClass;
    2775       26503 :       else if (RegVT == MVT::i64)
    2776             :         RC = &AArch64::GPR64RegClass;
    2777       19212 :       else if (RegVT == MVT::f16)
    2778             :         RC = &AArch64::FPR16RegClass;
    2779       18254 :       else if (RegVT == MVT::f32)
    2780             :         RC = &AArch64::FPR32RegClass;
    2781       16743 :       else if (RegVT == MVT::f64 || RegVT.is64BitVector())
    2782             :         RC = &AArch64::FPR64RegClass;
    2783        9203 :       else if (RegVT == MVT::f128 || RegVT.is128BitVector())
    2784             :         RC = &AArch64::FPR128RegClass;
    2785             :       else
    2786           0 :         llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
    2787             : 
    2788             :       // Transform the arguments in physical registers into virtual ones.
    2789       19666 :       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
    2790       19666 :       ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
    2791             : 
    2792             :       // If this is an 8, 16 or 32-bit value, it is really passed promoted
    2793             :       // to 64 bits.  Insert an assert[sz]ext to capture this, then
    2794             :       // truncate to the right size.
    2795       19666 :       switch (VA.getLocInfo()) {
    2796           0 :       default:
    2797           0 :         llvm_unreachable("Unknown loc info!");
    2798             :       case CCValAssign::Full:
    2799             :         break;
    2800        1623 :       case CCValAssign::BCvt:
    2801        3246 :         ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
    2802        1623 :         break;
    2803             :       case CCValAssign::AExt:
    2804             :       case CCValAssign::SExt:
    2805             :       case CCValAssign::ZExt:
    2806             :         // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
    2807             :         // nodes after our lowering.
    2808             :         assert(RegVT == Ins[i].VT && "incorrect register location selected");
    2809             :         break;
    2810             :       }
    2811             : 
    2812       19666 :       InVals.push_back(ArgValue);
    2813             : 
    2814             :     } else { // VA.isRegLoc()
    2815             :       assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
    2816         436 :       unsigned ArgOffset = VA.getLocMemOffset();
    2817         436 :       unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
    2818             : 
    2819         436 :       uint32_t BEAlign = 0;
    2820         442 :       if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
    2821          18 :           !Ins[i].Flags.isInConsecutiveRegs())
    2822           4 :         BEAlign = 8 - ArgSize;
    2823             : 
    2824         436 :       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
    2825             : 
    2826             :       // Create load nodes to retrieve arguments from the stack.
    2827        1744 :       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
    2828         436 :       SDValue ArgValue;
    2829             : 
    2830             :       // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
    2831         436 :       ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
    2832         436 :       MVT MemVT = VA.getValVT();
    2833             : 
    2834         436 :       switch (VA.getLocInfo()) {
    2835             :       default:
    2836             :         break;
    2837          15 :       case CCValAssign::BCvt:
    2838          15 :         MemVT = VA.getLocVT();
    2839          15 :         break;
    2840           8 :       case CCValAssign::SExt:
    2841           8 :         ExtType = ISD::SEXTLOAD;
    2842           8 :         break;
    2843           5 :       case CCValAssign::ZExt:
    2844           5 :         ExtType = ISD::ZEXTLOAD;
    2845           5 :         break;
    2846           9 :       case CCValAssign::AExt:
    2847           9 :         ExtType = ISD::EXTLOAD;
    2848           9 :         break;
    2849             :       }
    2850             : 
    2851         436 :       ArgValue = DAG.getExtLoad(
    2852             :           ExtType, DL, VA.getLocVT(), Chain, FIN,
    2853             :           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
    2854        1744 :           MemVT);
    2855             : 
    2856         436 :       InVals.push_back(ArgValue);
    2857             :     }
    2858             :   }
    2859             : 
    2860             :   // varargs
    2861       10565 :   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
    2862       10565 :   if (isVarArg) {
    2863          37 :     if (!Subtarget->isTargetDarwin() || IsWin64) {
    2864             :       // The AAPCS variadic function ABI is identical to the non-variadic
    2865             :       // one. As a result there may be more arguments in registers and we should
    2866             :       // save them for future reference.
    2867             :       // Win64 variadic functions also pass arguments in registers, but all float
    2868             :       // arguments are passed in integer registers.
    2869          19 :       saveVarArgRegisters(CCInfo, DAG, DL, Chain);
    2870             :     }
    2871             : 
    2872             :     // This will point to the next argument passed via stack.
    2873          28 :     unsigned StackOffset = CCInfo.getNextStackOffset();
    2874             :     // We currently pass all varargs at 8-byte alignment.
    2875          28 :     StackOffset = ((StackOffset + 7) & ~7);
    2876          28 :     FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
    2877             :   }
    2878             : 
    2879       10565 :   unsigned StackArgSize = CCInfo.getNextStackOffset();
    2880       10565 :   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
    2881       10565 :   if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
    2882             :     // This is a non-standard ABI so by fiat I say we're allowed to make full
    2883             :     // use of the stack area to be popped, which must be aligned to 16 bytes in
    2884             :     // any case:
    2885          42 :     StackArgSize = alignTo(StackArgSize, 16);
    2886             : 
    2887             :     // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
    2888             :     // a multiple of 16.
    2889          21 :     FuncInfo->setArgumentStackToRestore(StackArgSize);
    2890             : 
    2891             :     // This realignment carries over to the available bytes below. Our own
    2892             :     // callers will guarantee the space is free by giving an aligned value to
    2893             :     // CALLSEQ_START.
    2894             :   }
    2895             :   // Even if we're not expected to free up the space, it's useful to know how
    2896             :   // much is there while considering tail calls (because we can reuse it).
    2897       21130 :   FuncInfo->setBytesInStackArgArea(StackArgSize);
    2898             : 
    2899       21130 :   return Chain;
    2900             : }
    2901             : 
    2902          19 : void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
    2903             :                                                 SelectionDAG &DAG,
    2904             :                                                 const SDLoc &DL,
    2905             :                                                 SDValue &Chain) const {
    2906          19 :   MachineFunction &MF = DAG.getMachineFunction();
    2907          19 :   MachineFrameInfo &MFI = MF.getFrameInfo();
    2908          19 :   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
    2909          57 :   auto PtrVT = getPointerTy(DAG.getDataLayout());
    2910          57 :   bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv());
    2911             : 
    2912          38 :   SmallVector<SDValue, 8> MemOps;
    2913             : 
    2914             :   static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
    2915             :                                           AArch64::X3, AArch64::X4, AArch64::X5,
    2916             :                                           AArch64::X6, AArch64::X7 };
    2917             :   static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
    2918          38 :   unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
    2919             : 
    2920          19 :   unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
    2921          19 :   int GPRIdx = 0;
    2922          19 :   if (GPRSaveSize != 0) {
    2923          13 :     if (IsWin64) {
    2924           8 :       GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
    2925           8 :       if (GPRSaveSize & 15)
    2926             :         // The extra size here, if triggered, will always be 8.
    2927          14 :         MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
    2928             :     } else
    2929           5 :       GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
    2930             : 
    2931          13 :     SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
    2932             : 
    2933          85 :     for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
    2934          72 :       unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
    2935          72 :       SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
    2936             :       SDValue Store = DAG.getStore(
    2937             :           Val.getValue(1), DL, Val, FIN,
    2938             :           IsWin64
    2939             :               ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
    2940             :                                                   GPRIdx,
    2941          39 :                                                   (i - FirstVariadicGPR) * 8)
    2942         183 :               : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
    2943          72 :       MemOps.push_back(Store);
    2944          72 :       FIN =
    2945         288 :           DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
    2946             :     }
    2947             :   }
    2948          38 :   FuncInfo->setVarArgsGPRIndex(GPRIdx);
    2949          38 :   FuncInfo->setVarArgsGPRSize(GPRSaveSize);
    2950             : 
    2951          19 :   if (Subtarget->hasFPARMv8() && !IsWin64) {
    2952             :     static const MCPhysReg FPRArgRegs[] = {
    2953             :         AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
    2954             :         AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
    2955             :     static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
    2956           6 :     unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
    2957             : 
    2958           6 :     unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
    2959           6 :     int FPRIdx = 0;
    2960           6 :     if (FPRSaveSize != 0) {
    2961           5 :       FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
    2962             : 
    2963           5 :       SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
    2964             : 
    2965          41 :       for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
    2966          36 :         unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
    2967          36 :         SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
    2968             : 
    2969             :         SDValue Store = DAG.getStore(
    2970             :             Val.getValue(1), DL, Val, FIN,
    2971          72 :             MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
    2972          36 :         MemOps.push_back(Store);
    2973          36 :         FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
    2974         144 :                           DAG.getConstant(16, DL, PtrVT));
    2975             :       }
    2976             :     }
    2977          12 :     FuncInfo->setVarArgsFPRIndex(FPRIdx);
    2978           6 :     FuncInfo->setVarArgsFPRSize(FPRSaveSize);
    2979             :   }
    2980             : 
    2981          19 :   if (!MemOps.empty()) {
    2982          42 :     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
    2983             :   }
    2984          19 : }
    2985             : 
    2986             : /// LowerCallResult - Lower the result values of a call into the
    2987             : /// appropriate copies out of appropriate physical registers.
    2988        1534 : SDValue AArch64TargetLowering::LowerCallResult(
    2989             :     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
    2990             :     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
    2991             :     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
    2992             :     SDValue ThisVal) const {
    2993        1534 :   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
    2994        1534 :                           ? RetCC_AArch64_WebKit_JS
    2995             :                           : RetCC_AArch64_AAPCS;
    2996             :   // Assign locations to each value returned by this call.
    2997        3068 :   SmallVector<CCValAssign, 16> RVLocs;
    2998             :   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
    2999        3068 :                  *DAG.getContext());
    3000        1534 :   CCInfo.AnalyzeCallResult(Ins, RetCC);
    3001             : 
    3002             :   // Copy all of the result registers out of their specified physreg.
    3003        5262 :   for (unsigned i = 0; i != RVLocs.size(); ++i) {
    3004        2194 :     CCValAssign VA = RVLocs[i];
    3005             : 
    3006             :     // Pass 'this' value directly from the argument to return value, to avoid
    3007             :     // reg unit interference
    3008        1104 :     if (i == 0 && isThisReturn) {
    3009             :       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
    3010             :              "unexpected return calling convention register assignment");
    3011           7 :       InVals.push_back(ThisVal);
    3012           7 :       continue;
    3013             :     }
    3014             : 
    3015             :     SDValue Val =
    3016        2180 :         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
    3017        2180 :     Chain = Val.getValue(1);
    3018        2180 :     InFlag = Val.getValue(2);
    3019             : 
    3020        1090 :     switch (VA.getLocInfo()) {
    3021           0 :     default:
    3022           0 :       llvm_unreachable("Unknown loc info!");
    3023             :     case CCValAssign::Full:
    3024             :       break;
    3025         136 :     case CCValAssign::BCvt:
    3026         272 :       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
    3027         136 :       break;
    3028             :     }
    3029             : 
    3030        1090 :     InVals.push_back(Val);
    3031             :   }
    3032             : 
    3033        3068 :   return Chain;
    3034             : }
    3035             : 
    3036             : /// Return true if the calling convention is one that we can guarantee TCO for.
    3037             : static bool canGuaranteeTCO(CallingConv::ID CC) {
    3038          12 :   return CC == CallingConv::Fast;
    3039             : }
    3040             : 
    3041             : /// Return true if we might ever do TCO for calls with this calling convention.
    3042             : static bool mayTailCallThisCC(CallingConv::ID CC) {
    3043             :   switch (CC) {
    3044             :   case CallingConv::C:
    3045             :   case CallingConv::PreserveMost:
    3046             :   case CallingConv::Swift:
    3047             :     return true;
    3048          12 :   default:
    3049          12 :     return canGuaranteeTCO(CC);
    3050             :   }
    3051             : }
    3052             : 
    3053         214 : bool AArch64TargetLowering::isEligibleForTailCallOptimization(
    3054             :     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
    3055             :     const SmallVectorImpl<ISD::OutputArg> &Outs,
    3056             :     const SmallVectorImpl<SDValue> &OutVals,
    3057             :     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
    3058          12 :   if (!mayTailCallThisCC(CalleeCC))
    3059             :     return false;
    3060             : 
    3061         211 :   MachineFunction &MF = DAG.getMachineFunction();
    3062         211 :   const Function *CallerF = MF.getFunction();
    3063         211 :   CallingConv::ID CallerCC = CallerF->getCallingConv();
    3064         211 :   bool CCMatch = CallerCC == CalleeCC;
    3065             : 
    3066             :   // Byval parameters hand the function a pointer directly into the stack area
    3067             :   // we want to reuse during a tail call. Working around this *is* possible (see
    3068             :   // X86) but less efficient and uglier in LowerCall.
    3069         452 :   for (Function::const_arg_iterator i = CallerF->arg_begin(),
    3070         211 :                                     e = CallerF->arg_end();
    3071         452 :        i != e; ++i)
    3072         241 :     if (i->hasByValAttr())
    3073             :       return false;
    3074             : 
    3075         211 :   if (getTargetMachine().Options.GuaranteedTailCallOpt)
    3076           8 :     return canGuaranteeTCO(CalleeCC) && CCMatch;
    3077             : 
    3078             :   // Externally-defined functions with weak linkage should not be
    3079             :   // tail-called on AArch64 when the OS does not support dynamic
    3080             :   // pre-emption of symbols, as the AAELF spec requires normal calls
    3081             :   // to undefined weak functions to be replaced with a NOP or jump to the
    3082             :   // next instruction. The behaviour of branch instructions in this
    3083             :   // situation (as used for tail calls) is implementation-defined, so we
    3084             :   // cannot rely on the linker replacing the tail call with a return.
    3085         190 :   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
    3086         190 :     const GlobalValue *GV = G->getGlobal();
    3087         380 :     const Triple &TT = getTargetMachine().getTargetTriple();
    3088         190 :     if (GV->hasExternalWeakLinkage() &&
    3089           0 :         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
    3090             :       return false;
    3091             :   }
    3092             : 
    3093             :   // Now we search for cases where we can use a tail call without changing the
    3094             :   // ABI. Sibcall is used in some places (particularly gcc) to refer to this
    3095             :   // concept.
    3096             : 
    3097             :   // I want anyone implementing a new calling convention to think long and hard
    3098             :   // about this assert.
    3099             :   assert((!isVarArg || CalleeCC == CallingConv::C) &&
    3100             :          "Unexpected variadic calling convention");
    3101             : 
    3102         203 :   LLVMContext &C = *DAG.getContext();
    3103         203 :   if (isVarArg && !Outs.empty()) {
    3104             :     // At least two cases here: if caller is fastcc then we can't have any
    3105             :     // memory arguments (we'd be expected to clean up the stack afterwards). If
    3106             :     // caller is C then we could potentially use its argument area.
    3107             : 
    3108             :     // FIXME: for now we take the most conservative of these in both cases:
    3109             :     // disallow all variadic memory operands.
    3110           2 :     SmallVector<CCValAssign, 16> ArgLocs;
    3111           2 :     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
    3112             : 
    3113           2 :     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
    3114          14 :     for (const CCValAssign &ArgLoc : ArgLocs)
    3115          10 :       if (!ArgLoc.isRegLoc())
    3116           2 :         return false;
    3117             :   }
    3118             : 
    3119             :   // Check that the call results are passed in the same way.
    3120         201 :   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
    3121             :                                   CCAssignFnForCall(CalleeCC, isVarArg),
    3122             :                                   CCAssignFnForCall(CallerCC, isVarArg)))
    3123             :     return false;
    3124             :   // The callee has to preserve all registers the caller needs to preserve.
    3125         402 :   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
    3126         201 :   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
    3127         201 :   if (!CCMatch) {
    3128           7 :     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
    3129           7 :     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
    3130             :       return false;
    3131             :   }
    3132             : 
    3133             :   // Nothing more to check if the callee is taking no arguments
    3134         197 :   if (Outs.empty())
    3135             :     return true;
    3136             : 
    3137         158 :   SmallVector<CCValAssign, 16> ArgLocs;
    3138         316 :   CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
    3139             : 
    3140         158 :   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
    3141             : 
    3142         158 :   const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
    3143             : 
    3144             :   // If the stack arguments for this call do not fit into our own save area then
    3145             :   // the call cannot be made tail.
    3146         158 :   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
    3147             :     return false;
    3148             : 
    3149         130 :   const MachineRegisterInfo &MRI = MF.getRegInfo();
    3150         130 :   if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
    3151             :     return false;
    3152             : 
    3153         126 :   return true;
    3154             : }
    3155             : 
    3156          11 : SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
    3157             :                                                    SelectionDAG &DAG,
    3158             :                                                    MachineFrameInfo &MFI,
    3159             :                                                    int ClobberedFI) const {
    3160          22 :   SmallVector<SDValue, 8> ArgChains;
    3161          11 :   int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
    3162          11 :   int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
    3163             : 
    3164             :   // Include the original chain at the beginning of the list. When this is
    3165             :   // used by target LowerCall hooks, this helps legalize find the
    3166             :   // CALLSEQ_BEGIN node.
    3167          11 :   ArgChains.push_back(Chain);
    3168             : 
    3169             :   // Add a chain value for each stack argument corresponding
    3170          22 :   for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
    3171          33 :                             UE = DAG.getEntryNode().getNode()->use_end();
    3172         120 :        U != UE; ++U)
    3173         127 :     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
    3174          36 :       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
    3175          18 :         if (FI->getIndex() < 0) {
    3176          36 :           int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
    3177          18 :           int64_t InLastByte = InFirstByte;
    3178          36 :           InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
    3179             : 
    3180          27 :           if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
    3181           9 :               (FirstByte <= InFirstByte && InFirstByte <= LastByte))
    3182           9 :             ArgChains.push_back(SDValue(L, 1));
    3183             :         }
    3184             : 
    3185             :   // Build a tokenfactor for all the chains.
    3186          66 :   return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
    3187             : }
    3188             : 
    3189       12099 : bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
    3190             :                                                    bool TailCallOpt) const {
    3191       12099 :   return CallCC == CallingConv::Fast && TailCallOpt;
    3192             : }
    3193             : 
    3194             : /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
    3195             : /// and add input and output parameter nodes.
    3196             : SDValue
    3197        1706 : AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
    3198             :                                  SmallVectorImpl<SDValue> &InVals) const {
    3199        1706 :   SelectionDAG &DAG = CLI.DAG;
    3200        1706 :   SDLoc &DL = CLI.DL;
    3201        1706 :   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
    3202        1706 :   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
    3203        1706 :   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
    3204        1706 :   SDValue Chain = CLI.Chain;
    3205        1706 :   SDValue Callee = CLI.Callee;
    3206        1706 :   bool &IsTailCall = CLI.IsTailCall;
    3207        1706 :   CallingConv::ID CallConv = CLI.CallConv;
    3208        1706 :   bool IsVarArg = CLI.IsVarArg;
    3209             : 
    3210        1706 :   MachineFunction &MF = DAG.getMachineFunction();
    3211        1706 :   bool IsThisReturn = false;
    3212             : 
    3213        1706 :   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
    3214        1706 :   bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
    3215        1706 :   bool IsSibCall = false;
    3216             : 
    3217        1706 :   if (IsTailCall) {
    3218             :     // Check if it's really possible to do a tail call.
    3219         214 :     IsTailCall = isEligibleForTailCallOptimization(
    3220             :         Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
    3221         256 :     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
    3222           0 :       report_fatal_error("failed to perform tail call elimination on a call "
    3223             :                          "site marked musttail");
    3224             : 
    3225             :     // A sibling call is one where we're under the usual C ABI and not planning
    3226             :     // to change that but can still do a tail call:
    3227         420 :     if (!TailCallOpt && IsTailCall)
    3228         165 :       IsSibCall = true;
    3229             : 
    3230             :     if (IsTailCall)
    3231             :       ++NumTailCalls;
    3232             :   }
    3233             : 
    3234             :   // Analyze operands of the call, assigning locations to each operand.
    3235        3412 :   SmallVector<CCValAssign, 16> ArgLocs;
    3236             :   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
    3237        3412 :                  *DAG.getContext());
    3238             : 
    3239        1706 :   if (IsVarArg) {
    3240             :     // Handle fixed and variable vector arguments differently.
    3241             :     // Variable vector arguments always go into memory.
    3242          58 :     unsigned NumArgs = Outs.size();
    3243             : 
    3244         138 :     for (unsigned i = 0; i != NumArgs; ++i) {
    3245         218 :       MVT ArgVT = Outs[i].VT;
    3246         218 :       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
    3247         109 :       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
    3248         327 :                                                /*IsVarArg=*/ !Outs[i].IsFixed);
    3249         109 :       bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
    3250             :       assert(!Res && "Call operand has unhandled type");
    3251             :       (void)Res;
    3252             :     }
    3253             :   } else {
    3254             :     // At this point, Outs[].VT may already be promoted to i32. To correctly
    3255             :     // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
    3256             :     // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
    3257             :     // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
    3258             :     // we use a special version of AnalyzeCallOperands to pass in ValVT and
    3259             :     // LocVT.
    3260        3354 :     unsigned NumArgs = Outs.size();
    3261        4924 :     for (unsigned i = 0; i != NumArgs; ++i) {
    3262        6494 :       MVT ValVT = Outs[i].VT;
    3263             :       // Get type of the original argument.
    3264             :       EVT ActualVT = getValueType(DAG.getDataLayout(),
    3265        9741 :                                   CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
    3266        9741 :                                   /*AllowUnknown*/ true);
    3267        3247 :       MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
    3268        6494 :       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
    3269             :       // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
    3270        3247 :       if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
    3271             :         ValVT = MVT::i8;
    3272        3177 :       else if (ActualMVT == MVT::i16)
    3273          25 :         ValVT = MVT::i16;
    3274             : 
    3275        3247 :       CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
    3276        3247 :       bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
    3277             :       assert(!Res && "Call operand has unhandled type");
    3278             :       (void)Res;
    3279             :     }
    3280             :   }
    3281             : 
    3282             :   // Get a count of how many bytes are to be pushed on the stack.
    3283        1706 :   unsigned NumBytes = CCInfo.getNextStackOffset();
    3284             : 
    3285        1706 :   if (IsSibCall) {
    3286             :     // Since we're not changing the ABI to make this a tail call, the memory
    3287             :     // operands are already available in the caller's incoming argument space.
    3288         165 :     NumBytes = 0;
    3289             :   }
    3290             : 
    3291             :   // FPDiff is the byte offset of the call's argument area from the callee's.
    3292             :   // Stores to callee stack arguments will be placed in FixedStackSlots offset
    3293             :   // by this amount for a tail call. In a sibling call it must be 0 because the
    3294             :   // caller will deallocate the entire stack and the callee still expects its
    3295             :   // arguments to begin at SP+0. Completely unused for non-tail calls.
    3296        1706 :   int FPDiff = 0;
    3297             : 
    3298        1706 :   if (IsTailCall && !IsSibCall) {
    3299           7 :     unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
    3300             : 
    3301             :     // Since callee will pop argument stack as a tail call, we must keep the
    3302             :     // popped size 16-byte aligned.
    3303          14 :     NumBytes = alignTo(NumBytes, 16);
    3304             : 
    3305             :     // FPDiff will be negative if this tail call requires more space than we
    3306             :     // would automatically have in our incoming argument space. Positive if we
    3307             :     // can actually shrink the stack.
    3308           7 :     FPDiff = NumReusableBytes - NumBytes;
    3309             : 
    3310             :     // The stack pointer must be 16-byte aligned at all times it's used for a
    3311             :     // memory operation, which in practice means at *all* times and in
    3312             :     // particular across call boundaries. Therefore our own arguments started at
    3313             :     // a 16-byte aligned SP and the delta applied for the tail call should
    3314             :     // satisfy the same constraint.
    3315             :     assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
    3316             :   }
    3317             : 
    3318             :   // Adjust the stack pointer for the new arguments...
    3319             :   // These operations are automatically eliminated by the prolog/epilog pass
    3320        1706 :   if (!IsSibCall)
    3321        1541 :     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
    3322             : 
    3323             :   SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
    3324        6824 :                                         getPointerTy(DAG.getDataLayout()));
    3325             : 
    3326        3412 :   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
    3327        3412 :   SmallVector<SDValue, 8> MemOpChains;
    3328        5118 :   auto PtrVT = getPointerTy(DAG.getDataLayout());
    3329             : 
    3330             :   // Walk the register/memloc assignments, inserting copies/loads.
    3331        6768 :   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
    3332             :        ++i, ++realArgIdx) {
    3333        6712 :     CCValAssign &VA = ArgLocs[i];
    3334        6712 :     SDValue Arg = OutVals[realArgIdx];
    3335        6712 :     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
    3336             : 
    3337             :     // Promote the value if needed.
    3338        3356 :     switch (VA.getLocInfo()) {
    3339           0 :     default:
    3340           0 :       llvm_unreachable("Unknown loc info!");
    3341             :     case CCValAssign::Full:
    3342             :       break;
    3343          25 :     case CCValAssign::SExt:
    3344          50 :       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
    3345          25 :       break;
    3346          12 :     case CCValAssign::ZExt:
    3347          24 :       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
    3348          12 :       break;
    3349          87 :     case CCValAssign::AExt:
    3350         175 :       if (Outs[realArgIdx].ArgVT == MVT::i1) {
    3351             :         // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
    3352           2 :         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
    3353           2 :         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
    3354             :       }
    3355         174 :       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
    3356          87 :       break;
    3357         219 :     case CCValAssign::BCvt:
    3358         438 :       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
    3359         219 :       break;
    3360           0 :     case CCValAssign::FPExt:
    3361           0 :       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
    3362           0 :       break;
    3363             :     }
    3364             : 
    3365        3356 :     if (VA.isRegLoc()) {
    3366        4022 :       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
    3367          30 :           Outs[0].VT == MVT::i64) {
    3368             :         assert(VA.getLocVT() == MVT::i64 &&
    3369             :                "unexpected calling convention register assignment");
    3370             :         assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
    3371             :                "unexpected use of 'returned'");
    3372             :         IsThisReturn = true;
    3373             :       }
    3374        5184 :       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
    3375             :     } else {
    3376             :       assert(VA.isMemLoc());
    3377             : 
    3378         764 :       SDValue DstAddr;
    3379         764 :       MachinePointerInfo DstInfo;
    3380             : 
    3381             :       // FIXME: This works on big-endian for composite byvals, which are the
    3382             :       // common case. It should also work for fundamental types too.
    3383         764 :       uint32_t BEAlign = 0;
    3384        1524 :       unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
    3385        1524 :                                         : VA.getValVT().getSizeInBits();
    3386         764 :       OpSize = (OpSize + 7) / 8;
    3387         774 :       if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
    3388          10 :           !Flags.isInConsecutiveRegs()) {
    3389           8 :         if (OpSize < 8)
    3390           6 :           BEAlign = 8 - OpSize;
    3391             :       }
    3392         764 :       unsigned LocMemOffset = VA.getLocMemOffset();
    3393         764 :       int32_t Offset = LocMemOffset + BEAlign;
    3394         764 :       SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
    3395        1528 :       PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
    3396             : 
    3397         764 :       if (IsTailCall) {
    3398          11 :         Offset = Offset + FPDiff;
    3399          11 :         int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
    3400             : 
    3401          11 :         DstAddr = DAG.getFrameIndex(FI, PtrVT);
    3402          11 :         DstInfo =
    3403          22 :             MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
    3404             : 
    3405             :         // Make sure any stack arguments overlapping with where we're storing
    3406             :         // are loaded before this eventual operation. Otherwise they'll be
    3407             :         // clobbered.
    3408          11 :         Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
    3409             :       } else {
    3410         753 :         SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
    3411             : 
    3412        1506 :         DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
    3413         753 :         DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
    3414         753 :                                                LocMemOffset);
    3415             :       }
    3416             : 
    3417        2292 :       if (Outs[i].Flags.isByVal()) {
    3418             :         SDValue SizeNode =
    3419           8 :             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
    3420             :         SDValue Cpy = DAG.getMemcpy(
    3421           8 :             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
    3422             :             /*isVol = */ false, /*AlwaysInline = */ false,
    3423             :             /*isTailCall = */ false,
    3424          12 :             DstInfo, MachinePointerInfo());
    3425             : 
    3426           4 :         MemOpChains.push_back(Cpy);
    3427             :       } else {
    3428             :         // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
    3429             :         // promoted to a legal register type i32, we should truncate Arg back to
    3430             :         // i1/i8/i16.
    3431        1504 :         if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
    3432         744 :             VA.getValVT() == MVT::i16)
    3433          46 :           Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
    3434             : 
    3435         760 :         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
    3436         760 :         MemOpChains.push_back(Store);
    3437             :       }
    3438             :     }
    3439             :   }
    3440             : 
    3441        1706 :   if (!MemOpChains.empty())
    3442         297 :     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
    3443             : 
    3444             :   // Build a sequence of copy-to-reg nodes chained together with token chain
    3445             :   // and flag operands which copy the outgoing args into the appropriate regs.
    3446        1706 :   SDValue InFlag;
    3447        7710 :   for (auto &RegToPass : RegsToPass) {
    3448        2592 :     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
    3449        2592 :                              RegToPass.second, InFlag);
    3450        5184 :     InFlag = Chain.getValue(1);
    3451             :   }
    3452             : 
    3453             :   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
    3454             :   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
    3455             :   // node so that legalize doesn't hack it.
    3456        1194 :   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
    3457        1194 :     auto GV = G->getGlobal();
    3458        1194 :     if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
    3459             :         AArch64II::MO_GOT) {
    3460           4 :       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
    3461           4 :       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
    3462             :     } else {
    3463        1192 :       const GlobalValue *GV = G->getGlobal();
    3464        2384 :       Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
    3465             :     }
    3466         466 :   } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
    3467         469 :     if (getTargetMachine().getCodeModel() == CodeModel::Large &&
    3468           6 :         Subtarget->isTargetMachO()) {
    3469           0 :       const char *Sym = S->getSymbol();
    3470           0 :       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
    3471           0 :       Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
    3472             :     } else {
    3473         466 :       const char *Sym = S->getSymbol();
    3474         466 :       Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
    3475             :     }
    3476             :   }
    3477             : 
    3478             :   // We don't usually want to end the call-sequence here because we would tidy
    3479             :   // the frame up *after* the call, however in the ABI-changing tail-call case
    3480             :   // we've carefully laid out the parameters so that when sp is reset they'll be
    3481             :   // in the correct location.
    3482        1706 :   if (IsTailCall && !IsSibCall) {
    3483           7 :     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
    3484           7 :                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
    3485          14 :     InFlag = Chain.getValue(1);
    3486             :   }
    3487             : 
    3488        3412 :   std::vector<SDValue> Ops;
    3489        1706 :   Ops.push_back(Chain);
    3490        1706 :   Ops.push_back(Callee);
    3491             : 
    3492        1706 :   if (IsTailCall) {
    3493             :     // Each tail call may have to adjust the stack by a different amount, so
    3494             :     // this information must travel along with the operation for eventual
    3495             :     // consumption by emitEpilogue.
    3496         516 :     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
    3497             :   }
    3498             : 
    3499             :   // Add argument registers to the end of the list so that they are known live
    3500             :   // into the call.
    3501        7710 :   for (auto &RegToPass : RegsToPass)
    3502        5184 :     Ops.push_back(DAG.getRegister(RegToPass.first,
    3503        5184 :                                   RegToPass.second.getValueType()));
    3504             : 
    3505             :   // Add a register mask operand representing the call-preserved registers.
    3506             :   const uint32_t *Mask;
    3507        3412 :   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
    3508        1706 :   if (IsThisReturn) {
    3509             :     // For 'this' returns, use the X0-preserving mask if applicable
    3510          10 :     Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
    3511          10 :     if (!Mask) {
    3512           0 :       IsThisReturn = false;
    3513           0 :       Mask = TRI->getCallPreservedMask(MF, CallConv);
    3514             :     }
    3515             :   } else
    3516        1696 :     Mask = TRI->getCallPreservedMask(MF, CallConv);
    3517             : 
    3518             :   assert(Mask && "Missing call preserved mask for calling convention");
    3519        3412 :   Ops.push_back(DAG.getRegisterMask(Mask));
    3520             : 
    3521        1706 :   if (InFlag.getNode())
    3522        1409 :     Ops.push_back(InFlag);
    3523             : 
    3524        3412 :   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
    3525             : 
    3526             :   // If we're doing a tall call, use a TC_RETURN here rather than an
    3527             :   // actual call instruction.
    3528        1706 :   if (IsTailCall) {
    3529         172 :     MF.getFrameInfo().setHasTailCall();
    3530         172 :     return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
    3531             :   }
    3532             : 
    3533             :   // Returns a chain and a flag for retval copy to use.
    3534        1534 :   Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
    3535        3068 :   InFlag = Chain.getValue(1);
    3536             : 
    3537             :   uint64_t CalleePopBytes =
    3538        1553 :       DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
    3539             : 
    3540        1534 :   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
    3541             :                              DAG.getIntPtrConstant(CalleePopBytes, DL, true),
    3542        1534 :                              InFlag, DL);
    3543        1534 :   if (!Ins.empty())
    3544        1998 :     InFlag = Chain.getValue(1);
    3545             : 
    3546             :   // Handle result values, copying them out of physregs into vregs that we
    3547             :   // return.
    3548             :   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
    3549             :                          InVals, IsThisReturn,
    3550        1541 :                          IsThisReturn ? OutVals[0] : SDValue());
    3551             : }
    3552             : 
    3553       13605 : bool AArch64TargetLowering::CanLowerReturn(
    3554             :     CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
    3555             :     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
    3556       13605 :   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
    3557       13605 :                           ? RetCC_AArch64_WebKit_JS
    3558             :                           : RetCC_AArch64_AAPCS;
    3559       27210 :   SmallVector<CCValAssign, 16> RVLocs;
    3560       27210 :   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
    3561       27210 :   return CCInfo.CheckReturn(Outs, RetCC);
    3562             : }
    3563             : 
    3564             : SDValue
    3565       10573 : AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
    3566             :                                    bool isVarArg,
    3567             :                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
    3568             :                                    const SmallVectorImpl<SDValue> &OutVals,
    3569             :                                    const SDLoc &DL, SelectionDAG &DAG) const {
    3570       10573 :   CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
    3571       10573 :                           ? RetCC_AArch64_WebKit_JS
    3572             :                           : RetCC_AArch64_AAPCS;
    3573       21146 :   SmallVector<CCValAssign, 16> RVLocs;
    3574             :   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
    3575       21146 :                  *DAG.getContext());
    3576       10573 :   CCInfo.AnalyzeReturn(Outs, RetCC);
    3577             : 
    3578             :   // Copy the result values into the output registers.
    3579       10573 :   SDValue Flag;
    3580       21146 :   SmallVector<SDValue, 4> RetOps(1, Chain);
    3581       40634 :   for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
    3582             :        ++i, ++realRVLocIdx) {
    3583       19488 :     CCValAssign &VA = RVLocs[i];
    3584             :     assert(VA.isRegLoc() && "Can only return in registers!");
    3585       19488 :     SDValue Arg = OutVals[realRVLocIdx];
    3586             : 
    3587        9744 :     switch (VA.getLocInfo()) {
    3588           0 :     default:
    3589           0 :       llvm_unreachable("Unknown loc info!");
    3590        8677 :     case CCValAssign::Full:
    3591       17417 :       if (Outs[i].ArgVT == MVT::i1) {
    3592             :         // AAPCS requires i1 to be zero-extended to i8 by the producer of the
    3593             :         // value. This is strictly redundant on Darwin (which uses "zeroext
    3594             :         // i1"), but will be optimised out before ISel.
    3595         126 :         Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
    3596         126 :         Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
    3597             :       }
    3598             :       break;
    3599        1067 :     case CCValAssign::BCvt:
    3600        2134 :       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
    3601        1067 :       break;
    3602             :     }
    3603             : 
    3604        9744 :     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
    3605       19488 :     Flag = Chain.getValue(1);
    3606       19488 :     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
    3607             :   }
    3608       21146 :   const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
    3609             :   const MCPhysReg *I =
    3610       10573 :       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
    3611       10573 :   if (I) {
    3612         678 :     for (; *I; ++I) {
    3613         672 :       if (AArch64::GPR64RegClass.contains(*I))
    3614         144 :         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
    3615         384 :       else if (AArch64::FPR64RegClass.contains(*I))
    3616         384 :         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
    3617             :       else
    3618           0 :         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
    3619             :     }
    3620             :   }
    3621             : 
    3622       10573 :   RetOps[0] = Chain; // Update chain.
    3623             : 
    3624             :   // Add the flag if we have it.
    3625       10573 :   if (Flag.getNode())
    3626        8642 :     RetOps.push_back(Flag);
    3627             : 
    3628       42292 :   return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
    3629             : }
    3630             : 
    3631             : //===----------------------------------------------------------------------===//
    3632             : //  Other Lowering Code
    3633             : //===----------------------------------------------------------------------===//
    3634             : 
    3635        3901 : SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
    3636             :                                              SelectionDAG &DAG,
    3637             :                                              unsigned Flag) const {
    3638       15604 :   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
    3639             : }
    3640             : 
    3641          52 : SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
    3642             :                                              SelectionDAG &DAG,
    3643             :                                              unsigned Flag) const {
    3644         104 :   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
    3645             : }
    3646             : 
    3647         260 : SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
    3648             :                                              SelectionDAG &DAG,
    3649             :                                              unsigned Flag) const {
    3650             :   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
    3651         780 :                                    N->getOffset(), Flag);
    3652             : }
    3653             : 
    3654          16 : SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
    3655             :                                              SelectionDAG &DAG,
    3656             :                                              unsigned Flag) const {
    3657          32 :   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
    3658             : }
    3659             : 
    3660             : // (loadGOT sym)
    3661             : template <class NodeTy>
    3662         181 : SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG) const {
    3663             :   DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
    3664         362 :   SDLoc DL(N);
    3665         724 :   EVT Ty = getPointerTy(DAG.getDataLayout());
    3666         181 :   SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT);
    3667             :   // FIXME: Once remat is capable of dealing with instructions with register
    3668             :   // operands, expand this into two nodes instead of using a wrapper node.
    3669         362 :   return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
    3670             : }
    3671             : 
    3672             : // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
    3673             : template <class NodeTy>
    3674          29 : SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG)
    3675             :   const {
    3676             :   DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
    3677          58 :   SDLoc DL(N);
    3678         116 :   EVT Ty = getPointerTy(DAG.getDataLayout());
    3679          29 :   const unsigned char MO_NC = AArch64II::MO_NC;
    3680             :   return DAG.getNode(
    3681             :         AArch64ISD::WrapperLarge, DL, Ty,
    3682             :         getTargetNode(N, Ty, DAG, AArch64II::MO_G3),
    3683             :         getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC),
    3684             :         getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC),
    3685          58 :         getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC));
    3686             : }
    3687             : 
    3688             : // (addlow (adrp %hi(sym)) %lo(sym))
    3689             : template <class NodeTy>
    3690        1966 : SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG) const {
    3691             :   DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
    3692        3932 :   SDLoc DL(N);
    3693        7864 :   EVT Ty = getPointerTy(DAG.getDataLayout());
    3694        1966 :   SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE);
    3695        1966 :   SDValue Lo = getTargetNode(N, Ty, DAG,
    3696             :                              AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
    3697        1966 :   SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
    3698        3932 :   return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
    3699             : }
    3700             : 
    3701        2019 : SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
    3702             :                                                   SelectionDAG &DAG) const {
    3703        2019 :   GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
    3704        2019 :   const GlobalValue *GV = GN->getGlobal();
    3705             :   unsigned char OpFlags =
    3706        2019 :       Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
    3707             : 
    3708             :   assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
    3709             :          "unexpected offset in global node");
    3710             : 
    3711             :   // This also catches the large code model case for Darwin.
    3712        2019 :   if ((OpFlags & AArch64II::MO_GOT) != 0) {
    3713         181 :     return getGOT(GN, DAG);
    3714             :   }
    3715             : 
    3716        1838 :   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
    3717          22 :     return getAddrLarge(GN, DAG);
    3718             :   } else {
    3719        1816 :     return getAddr(GN, DAG);
    3720             :   }
    3721             : }
    3722             : 
    3723             : /// \brief Convert a TLS address reference into the correct sequence of loads
    3724             : /// and calls to compute the variable's address (for Darwin, currently) and
    3725             : /// return an SDValue containing the final node.
    3726             : 
    3727             : /// Darwin only has one TLS scheme which must be capable of dealing with the
    3728             : /// fully general situation, in the worst case. This means:
    3729             : ///     + "extern __thread" declaration.
    3730             : ///     + Defined in a possibly unknown dynamic library.
    3731             : ///
    3732             : /// The general system is that each __thread variable has a [3 x i64] descriptor
    3733             : /// which contains information used by the runtime to calculate the address. The
    3734             : /// only part of this the compiler needs to know about is the first xword, which
    3735             : /// contains a function pointer that must be called with the address of the
    3736             : /// entire descriptor in "x0".
    3737             : ///
    3738             : /// Since this descriptor may be in a different unit, in general even the
    3739             : /// descriptor must be accessed via an indirect load. The "ideal" code sequence
    3740             : /// is:
    3741             : ///     adrp x0, _var@TLVPPAGE
    3742             : ///     ldr x0, [x0, _var@TLVPPAGEOFF]   ; x0 now contains address of descriptor
    3743             : ///     ldr x1, [x0]                     ; x1 contains 1st entry of descriptor,
    3744             : ///                                      ; the function pointer
    3745             : ///     blr x1                           ; Uses descriptor address in x0
    3746             : ///     ; Address of _var is now in x0.
    3747             : ///
    3748             : /// If the address of _var's descriptor *is* known to the linker, then it can
    3749             : /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
    3750             : /// a slight efficiency gain.
    3751             : SDValue
    3752          24 : AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
    3753             :                                                    SelectionDAG &DAG) const {
    3754             :   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
    3755             : 
    3756          48 :   SDLoc DL(Op);
    3757          72 :   MVT PtrVT = getPointerTy(DAG.getDataLayout());
    3758          24 :   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
    3759             : 
    3760             :   SDValue TLVPAddr =
    3761          48 :       DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
    3762          48 :   SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
    3763             : 
    3764             :   // The first entry in the descriptor is a function pointer that we must call
    3765             :   // to obtain the address of the variable.
    3766          24 :   SDValue Chain = DAG.getEntryNode();
    3767             :   SDValue FuncTLVGet = DAG.getLoad(
    3768             :       MVT::i64, DL, Chain, DescAddr,
    3769             :       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
    3770             :       /* Alignment = */ 8,
    3771          48 :       MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
    3772          72 :           MachineMemOperand::MODereferenceable);
    3773          48 :   Chain = FuncTLVGet.getValue(1);
    3774             : 
    3775          24 :   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
    3776          24 :   MFI.setAdjustsStack(true);
    3777             : 
    3778             :   // TLS calls preserve all registers except those that absolutely must be
    3779             :   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
    3780             :   // silly).
    3781             :   const uint32_t *Mask =
    3782          48 :       Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
    3783             : 
    3784             :   // Finally, we can make the call. This is just a degenerate version of a
    3785             :   // normal AArch64 call node: x0 takes the address of the descriptor, and
    3786             :   // returns the address of the variable in this thread.
    3787          24 :   Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
    3788          24 :   Chain =
    3789          96 :       DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
    3790          24 :                   Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
    3791         120 :                   DAG.getRegisterMask(Mask), Chain.getValue(1));
    3792          96 :   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
    3793             : }
    3794             : 
    3795             : /// When accessing thread-local variables under either the general-dynamic or
    3796             : /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
    3797             : /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
    3798             : /// is a function pointer to carry out the resolution.
    3799             : ///
    3800             : /// The sequence is:
    3801             : ///    adrp  x0, :tlsdesc:var
    3802             : ///    ldr   x1, [x0, #:tlsdesc_lo12:var]
    3803             : ///    add   x0, x0, #:tlsdesc_lo12:var
    3804             : ///    .tlsdesccall var
    3805             : ///    blr   x1
    3806             : ///    (TPIDR_EL0 offset now in x0)
    3807             : ///
    3808             : ///  The above sequence must be produced unscheduled, to enable the linker to
    3809             : ///  optimize/relax this sequence.
    3810             : ///  Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
    3811             : ///  above sequence, and expanded really late in the compilation flow, to ensure
    3812             : ///  the sequence is produced as per above.
    3813          26 : SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
    3814             :                                                       const SDLoc &DL,
    3815             :                                                       SelectionDAG &DAG) const {
    3816         104 :   EVT PtrVT = getPointerTy(DAG.getDataLayout());
    3817             : 
    3818          26 :   SDValue Chain = DAG.getEntryNode();
    3819          52 :   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
    3820             : 
    3821          26 :   Chain =
    3822          78 :       DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
    3823          52 :   SDValue Glue = Chain.getValue(1);
    3824             : 
    3825          26 :   return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
    3826             : }
    3827             : 
    3828             : SDValue
    3829          54 : AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
    3830             :                                                 SelectionDAG &DAG) const {
    3831             :   assert(Subtarget->isTargetELF() && "This function expects an ELF target");
    3832             :   assert(Subtarget->useSmallAddressing() &&
    3833             :          "ELF TLS only supported in small memory model");
    3834             :   // Different choices can be made for the maximum size of the TLS area for a
    3835             :   // module. For the small address model, the default TLS size is 16MiB and the
    3836             :   // maximum TLS size is 4GiB.
    3837             :   // FIXME: add -mtls-size command line option and make it control the 16MiB
    3838             :   // vs. 4GiB code sequence generation.
    3839          54 :   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
    3840             : 
    3841          54 :   TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
    3842             : 
    3843          54 :   if (DAG.getTarget().Options.EmulatedTLS)
    3844          17 :     return LowerToTLSEmulatedModel(GA, DAG);
    3845             : 
    3846          37 :   if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
    3847          25 :     if (Model == TLSModel::LocalDynamic)
    3848           8 :       Model = TLSModel::GeneralDynamic;
    3849             :   }
    3850             : 
    3851          37 :   SDValue TPOff;
    3852         148 :   EVT PtrVT = getPointerTy(DAG.getDataLayout());
    3853          37 :   SDLoc DL(Op);
    3854          37 :   const GlobalValue *GV = GA->getGlobal();
    3855             : 
    3856          37 :   SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
    3857             : 
    3858          37 :   if (Model == TLSModel::LocalExec) {
    3859             :     SDValue HiVar = DAG.getTargetGlobalAddress(
    3860           7 :         GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
    3861             :     SDValue LoVar = DAG.getTargetGlobalAddress(
    3862             :         GV, DL, PtrVT, 0,
    3863           7 :         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
    3864             : 
    3865             :     SDValue TPWithOff_lo =
    3866          14 :         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
    3867             :                                    HiVar,
    3868           7 :                                    DAG.getTargetConstant(0, DL, MVT::i32)),
    3869           7 :                 0);
    3870             :     SDValue TPWithOff =
    3871           7 :         SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
    3872             :                                    LoVar,
    3873           7 :                                    DAG.getTargetConstant(0, DL, MVT::i32)),
    3874           7 :                 0);
    3875           7 :     return TPWithOff;
    3876          30 :   } else if (Model == TLSModel::InitialExec) {
    3877           4 :     TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
    3878           4 :     TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
    3879          26 :   } else if (Model == TLSModel::LocalDynamic) {
    3880             :     // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
    3881             :     // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
    3882             :     // the beginning of the module's TLS region, followed by a DTPREL offset
    3883             :     // calculation.
    3884             : 
    3885             :     // These accesses will need deduplicating if there's more than one.
    3886             :     AArch64FunctionInfo *MFI =
    3887          16 :         DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
    3888             :     MFI->incNumLocalDynamicTLSAccesses();
    3889             : 
    3890             :     // The call needs a relocation too for linker relaxation. It doesn't make
    3891             :     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
    3892             :     // the address.
    3893             :     SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
    3894           8 :                                                   AArch64II::MO_TLS);
    3895             : 
    3896             :     // Now we can calculate the offset from TPIDR_EL0 to this module's
    3897             :     // thread-local area.
    3898           8 :     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
    3899             : 
    3900             :     // Now use :dtprel_whatever: operations to calculate this variable's offset
    3901             :     // in its thread-storage area.
    3902             :     SDValue HiVar = DAG.getTargetGlobalAddress(
    3903          16 :         GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
    3904             :     SDValue LoVar = DAG.getTargetGlobalAddress(
    3905             :         GV, DL, MVT::i64, 0,
    3906          16 :         AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
    3907             : 
    3908           8 :     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
    3909           8 :                                        DAG.getTargetConstant(0, DL, MVT::i32)),
    3910             :                     0);
    3911           8 :     TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
    3912           8 :                                        DAG.getTargetConstant(0, DL, MVT::i32)),
    3913             :                     0);
    3914          18 :   } else if (Model == TLSModel::GeneralDynamic) {
    3915             :     // The call needs a relocation too for linker relaxation. It doesn't make
    3916             :     // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
    3917             :     // the address.
    3918             :     SDValue SymAddr =
    3919          18 :         DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
    3920             : 
    3921             :     // Finally we can make a call to calculate the offset from tpidr_el0.
    3922          18 :     TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
    3923             :   } else
    3924           0 :     llvm_unreachable("Unsupported ELF TLS access model");
    3925             : 
    3926          30 :   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
    3927             : }
    3928             : 
    3929          78 : SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
    3930             :                                                      SelectionDAG &DAG) const {
    3931         132 :   if (Subtarget->isTargetDarwin())
    3932          24 :     return LowerDarwinGlobalTLSAddress(Op, DAG);
    3933         108 :   if (Subtarget->isTargetELF())
    3934          54 :     return LowerELFGlobalTLSAddress(Op, DAG);
    3935             : 
    3936           0 :   llvm_unreachable("Unexpected platform trying to use TLS");
    3937             : }
    3938             : 
    3939         933 : SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
    3940        1866 :   SDValue Chain = Op.getOperand(0);
    3941        2799 :   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
    3942        1866 :   SDValue LHS = Op.getOperand(2);
    3943        1866 :   SDValue RHS = Op.getOperand(3);
    3944        1866 :   SDValue Dest = Op.getOperand(4);
    3945        1866 :   SDLoc dl(Op);
    3946             : 
    3947             :   // Handle f128 first, since lowering it will result in comparing the return
    3948             :   // value of a libcall against zero, which is just what the rest of LowerBR_CC
    3949             :   // is expecting to deal with.
    3950        1867 :   if (LHS.getValueType() == MVT::f128) {
    3951           2 :     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
    3952             : 
    3953             :     // If softenSetCCOperands returned a scalar, we need to compare the result
    3954             :     // against zero to select between true and false values.
    3955           1 :     if (!RHS.getNode()) {
    3956           0 :       RHS = DAG.getConstant(0, dl, LHS.getValueType());
    3957           0 :       CC = ISD::SETNE;
    3958             :     }
    3959             :   }
    3960             : 
    3961             :   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
    3962             :   // instruction.
    3963        1866 :   unsigned Opc = LHS.getOpcode();
    3964         947 :   if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
    3965             :       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
    3966          14 :        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
    3967             :     assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
    3968             :            "Unexpected condition code.");
    3969             :     // Only lower legal XALUO ops.
    3970          42 :     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
    3971           0 :       return SDValue();
    3972             : 
    3973             :     // The actual operation with overflow check.
    3974             :     AArch64CC::CondCode OFCC;
    3975             :     SDValue Value, Overflow;
    3976          56 :     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
    3977             : 
    3978          14 :     if (CC == ISD::SETNE)
    3979          28 :       OFCC = getInvertedCondCode(OFCC);
    3980          14 :     SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
    3981             : 
    3982             :     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
    3983          14 :                        Overflow);
    3984             :   }
    3985             : 
    3986        1838 :   if (LHS.getValueType().isInteger()) {
    3987             :     assert((LHS.getValueType() == RHS.getValueType()) &&
    3988             :            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
    3989             : 
    3990             :     // If the RHS of the comparison is zero, we can potentially fold this
    3991             :     // to a specialized branch.
    3992         729 :     const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
    3993         729 :     if (RHSC && RHSC->getZExtValue() == 0) {
    3994         495 :       if (CC == ISD::SETEQ) {
    3995             :         // See if we can use a TBZ to fold in an AND as well.
    3996             :         // TBZ has a smaller branch displacement than CBZ.  If the offset is
    3997             :         // out of bounds, a late MI-layer pass rewrites branches.
    3998             :         // 403.gcc is an example that hits this case.
    3999         191 :         if (LHS.getOpcode() == ISD::AND &&
    4000         288 :             isa<ConstantSDNode>(LHS.getOperand(1)) &&
    4001         274 :             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
    4002         160 :           SDValue Test = LHS.getOperand(0);
    4003         160 :           uint64_t Mask = LHS.getConstantOperandVal(1);
    4004             :           return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
    4005         160 :                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
    4006         160 :                              Dest);
    4007             :         }
    4008             : 
    4009         111 :         return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
    4010         304 :       } else if (CC == ISD::SETNE) {
    4011             :         // See if we can use a TBZ to fold in an AND as well.
    4012             :         // TBZ has a smaller branch displacement than CBZ.  If the offset is
    4013             :         // out of bounds, a late MI-layer pass rewrites branches.
    4014             :         // 403.gcc is an example that hits this case.
    4015         249 :         if (LHS.getOpcode() == ISD::AND &&
    4016         281 :             isa<ConstantSDNode>(LHS.getOperand(1)) &&
    4017          87 :             isPowerOf2_64(LHS.getConstantOperandVal(1))) {
    4018          50 :           SDValue Test = LHS.getOperand(0);
    4019          50 :           uint64_t Mask = LHS.getConstantOperandVal(1);
    4020             :           return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
    4021          50 :                              DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
    4022          50 :                              Dest);
    4023             :         }
    4024             : 
    4025         224 :         return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
    4026          84 :       } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
    4027             :         // Don't combine AND since emitComparison converts the AND to an ANDS
    4028             :         // (a.k.a. TST) and the test in the test bit and branch instruction
    4029             :         // becomes redundant.  This would also increase register pressure.
    4030          27 :         uint64_t Mask = LHS.getValueSizeInBits() - 1;
    4031             :         return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
    4032          54 :                            DAG.getConstant(Mask, dl, MVT::i64), Dest);
    4033             :       }
    4034             :     }
    4035         694 :     if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
    4036          22 :         LHS.getOpcode() != ISD::AND) {
    4037             :       // Don't combine AND since emitComparison converts the AND to an ANDS
    4038             :       // (a.k.a. TST) and the test in the test bit and branch instruction
    4039             :       // becomes redundant.  This would also increase register pressure.
    4040          20 :       uint64_t Mask = LHS.getValueSizeInBits() - 1;
    4041             :       return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
    4042          40 :                          DAG.getConstant(Mask, dl, MVT::i64), Dest);
    4043             :     }
    4044             : 
    4045         390 :     SDValue CCVal;
    4046         390 :     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
    4047             :     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
    4048         390 :                        Cmp);
    4049             :   }
    4050             : 
    4051             :   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
    4052             :          LHS.getValueType() == MVT::f64);
    4053             : 
    4054             :   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
    4055             :   // clean.  Some of them require two branches to implement.
    4056          42 :   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
    4057             :   AArch64CC::CondCode CC1, CC2;
    4058          42 :   changeFPCCToAArch64CC(CC, CC1, CC2);
    4059          42 :   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
    4060             :   SDValue BR1 =
    4061          42 :       DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
    4062          42 :   if (CC2 != AArch64CC::AL) {
    4063           5 :     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
    4064             :     return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
    4065           5 :                        Cmp);
    4066             :   }
    4067             : 
    4068          37 :   return BR1;
    4069             : }
    4070             : 
    4071          29 : SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
    4072             :                                               SelectionDAG &DAG) const {
    4073          58 :   EVT VT = Op.getValueType();
    4074          58 :   SDLoc DL(Op);
    4075             : 
    4076          58 :   SDValue In1 = Op.getOperand(0);
    4077          58 :   SDValue In2 = Op.getOperand(1);
    4078          58 :   EVT SrcVT = In2.getValueType();
    4079             : 
    4080          29 :   if (SrcVT.bitsLT(VT))
    4081           7 :     In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
    4082          22 :   else if (SrcVT.bitsGT(VT))
    4083          10 :     In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
    4084             : 
    4085          29 :   EVT VecVT;
    4086             :   uint64_t EltMask;
    4087          29 :   SDValue VecVal1, VecVal2;
    4088             : 
    4089          29 :   auto setVecVal = [&] (int Idx) {
    4090          58 :     if (!VT.isVector()) {
    4091         145 :       VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
    4092          48 :                                           DAG.getUNDEF(VecVT), In1);
    4093          29 :       VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
    4094          48 :                                           DAG.getUNDEF(VecVT), In2);
    4095             :     } else {
    4096          30 :       VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
    4097          30 :       VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
    4098             :     }
    4099          58 :   };
    4100             : 
    4101          62 :   if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
    4102          30 :     VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
    4103          15 :     EltMask = 0x80000000ULL;
    4104          15 :     setVecVal(AArch64::ssub);
    4105          24 :   } else if (VT == MVT::f64 || VT == MVT::v2f64) {
    4106          10 :     VecVT = MVT::v2i64;
    4107             : 
    4108             :     // We want to materialize a mask with the high bit set, but the AdvSIMD
    4109             :     // immediate moves cannot materialize that in a single instruction for
    4110             :     // 64-bit elements. Instead, materialize zero and then negate it.
    4111          10 :     EltMask = 0;
    4112             : 
    4113          10 :     setVecVal(AArch64::dsub);
    4114           4 :   } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
    4115           8 :     VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
    4116           4 :     EltMask = 0x8000ULL;
    4117           4 :     setVecVal(AArch64::hsub);
    4118             :   } else {
    4119           0 :     llvm_unreachable("Invalid type for copysign!");
    4120             :   }
    4121             : 
    4122          29 :   SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
    4123             : 
    4124             :   // If we couldn't materialize the mask above, then the mask vector will be
    4125             :   // the zero vector, and we need to negate it here.
    4126          54 :   if (VT == MVT::f64 || VT == MVT::v2f64) {
    4127          20 :     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
    4128          20 :     BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
    4129          20 :     BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
    4130             :   }
    4131             : 
    4132             :   SDValue Sel =
    4133          29 :       DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
    4134             : 
    4135          58 :   if (VT == MVT::f16)
    4136           4 :     return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
    4137          50 :   if (VT == MVT::f32)
    4138          11 :     return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
    4139          28 :   else if (VT == MVT::f64)
    4140           4 :     return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
    4141             :   else
    4142          10 :     return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
    4143             : }
    4144             : 
    4145          34 : SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
    4146          68 :   if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
    4147             :           Attribute::NoImplicitFloat))
    4148           4 :     return SDValue();
    4149             : 
    4150          30 :   if (!Subtarget->hasNEON())
    4151           3 :     return SDValue();
    4152             : 
    4153             :   // While there is no integer popcount instruction, it can
    4154             :   // be more efficiently lowered to the following sequence that uses
    4155             :   // AdvSIMD registers/instructions as long as the copies to/from
    4156             :   // the AdvSIMD registers are cheap.
    4157             :   //  FMOV    D0, X0        // copy 64-bit int to vector, high bits zero'd
    4158             :   //  CNT     V0.8B, V0.8B  // 8xbyte pop-counts
    4159             :   //  ADDV    B0, V0.8B     // sum 8xbyte pop-counts
    4160             :   //  UMOV    X0, V0.B[0]   // copy byte result back to integer reg
    4161          54 :   SDValue Val = Op.getOperand(0);
    4162          27 :   SDLoc DL(Op);
    4163          54 :   EVT VT = Op.getValueType();
    4164             : 
    4165          31 :   if (VT == MVT::i32)
    4166          46 :     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
    4167          54 :   Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
    4168             : 
    4169          54 :   SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
    4170             :   SDValue UaddLV = DAG.getNode(
    4171             :       ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
    4172          81 :       DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
    4173             : 
    4174          50 :   if (VT == MVT::i64)
    4175           8 :     UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
    4176          27 :   return UaddLV;
    4177             : }
    4178             : 
    4179         615 : SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
    4180             : 
    4181        1845 :   if (Op.getValueType().isVector())
    4182         499 :     return LowerVSETCC(Op, DAG);
    4183             : 
    4184         232 :   SDValue LHS = Op.getOperand(0);
    4185         232 :   SDValue RHS = Op.getOperand(1);
    4186         348 :   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
    4187         116 :   SDLoc dl(Op);
    4188             : 
    4189             :   // We chose ZeroOrOneBooleanContents, so use zero and one.
    4190         232 :   EVT VT = Op.getValueType();
    4191         116 :   SDValue TVal = DAG.getConstant(1, dl, VT);
    4192         116 :   SDValue FVal = DAG.getConstant(0, dl, VT);
    4193             : 
    4194             :   // Handle f128 first, since one possible outcome is a normal integer
    4195             :   // comparison which gets picked up by the next if statement.
    4196         237 :   if (LHS.getValueType() == MVT::f128) {
    4197          10 :     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
    4198             : 
    4199             :     // If softenSetCCOperands returned a scalar, use it.
    4200           5 :     if (!RHS.getNode()) {
    4201             :       assert(LHS.getValueType() == Op.getValueType() &&
    4202             :              "Unexpected setcc expansion!");
    4203           1 :       return LHS;
    4204             :     }
    4205             :   }
    4206             : 
    4207         230 :   if (LHS.getValueType().isInteger()) {
    4208          76 :     SDValue CCVal;
    4209             :     SDValue Cmp =
    4210          76 :         getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
    4211             : 
    4212             :     // Note that we inverted the condition above, so we reverse the order of
    4213             :     // the true and false operands here.  This will allow the setcc to be
    4214             :     // matched to a single CSINC instruction.
    4215          76 :     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
    4216             :   }
    4217             : 
    4218             :   // Now we know we're dealing with FP values.
    4219             :   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
    4220             :          LHS.getValueType() == MVT::f64);
    4221             : 
    4222             :   // If that fails, we'll need to perform an FCMP + CSEL sequence.  Go ahead
    4223             :   // and do the comparison.
    4224          39 :   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
    4225             : 
    4226             :   AArch64CC::CondCode CC1, CC2;
    4227          39 :   changeFPCCToAArch64CC(CC, CC1, CC2);
    4228          39 :   if (CC2 == AArch64CC::AL) {
    4229          35 :     changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
    4230          35 :     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
    4231             : 
    4232             :     // Note that we inverted the condition above, so we reverse the order of
    4233             :     // the true and false operands here.  This will allow the setcc to be
    4234             :     // matched to a single CSINC instruction.
    4235          35 :     return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
    4236             :   } else {
    4237             :     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
    4238             :     // totally clean.  Some of them require two CSELs to implement.  As is in
    4239             :     // this case, we emit the first CSEL and then emit a second using the output
    4240             :     // of the first as the RHS.  We're effectively OR'ing the two CC's together.
    4241             : 
    4242             :     // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
    4243           4 :     SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
    4244             :     SDValue CS1 =
    4245           4 :         DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
    4246             : 
    4247           4 :     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
    4248           4 :     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
    4249             :   }
    4250             : }
    4251             : 
    4252         473 : SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
    4253             :                                               SDValue RHS, SDValue TVal,
    4254             :                                               SDValue FVal, const SDLoc &dl,
    4255             :                                               SelectionDAG &DAG) const {
    4256             :   // Handle f128 first, because it will result in a comparison of some RTLIB
    4257             :   // call result against zero.
    4258         946 :   if (LHS.getValueType() == MVT::f128) {
    4259           0 :     softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
    4260             : 
    4261             :     // If softenSetCCOperands returned a scalar, we need to compare the result
    4262             :     // against zero to select between true and false values.
    4263           0 :     if (!RHS.getNode()) {
    4264           0 :       RHS = DAG.getConstant(0, dl, LHS.getValueType());
    4265           0 :       CC = ISD::SETNE;
    4266             :     }
    4267             :   }
    4268             : 
    4269             :   // Also handle f16, for which we need to do a f32 comparison.
    4270        1174 :   if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
    4271         340 :     LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
    4272         340 :     RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
    4273             :   }
    4274             : 
    4275             :   // Next, handle integers.
    4276         946 :   if (LHS.getValueType().isInteger()) {
    4277             :     assert((LHS.getValueType() == RHS.getValueType()) &&
    4278             :            (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
    4279             : 
    4280         201 :     unsigned Opcode = AArch64ISD::CSEL;
    4281             : 
    4282             :     // If both the TVal and the FVal are constants, see if we can swap them in
    4283             :     // order to for a CSINV or CSINC out of them.
    4284         201 :     ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
    4285          47 :     ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
    4286             : 
    4287          93 :     if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
    4288           8 :       std::swap(TVal, FVal);
    4289           8 :       std::swap(CTVal, CFVal);
    4290           8 :       CC = ISD::getSetCCInverse(CC, true);
    4291         269 :     } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
    4292           0 :       std::swap(TVal, FVal);
    4293           0 :       std::swap(CTVal, CFVal);
    4294           0 :       CC = ISD::getSetCCInverse(CC, true);
    4295         386 :     } else if (TVal.getOpcode() == ISD::XOR) {
    4296             :       // If TVal is a NOT we want to swap TVal and FVal so that we can match
    4297             :       // with a CSINV rather than a CSEL.
    4298          10 :       if (isAllOnesConstant(TVal.getOperand(1))) {
    4299           5 :         std::swap(TVal, FVal);
    4300           5 :         std::swap(CTVal, CFVal);
    4301           5 :         CC = ISD::getSetCCInverse(CC, true);
    4302             :       }
    4303         376 :     } else if (TVal.getOpcode() == ISD::SUB) {
    4304             :       // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
    4305             :       // that we can match with a CSNEG rather than a CSEL.
    4306          12 :       if (isNullConstant(TVal.getOperand(0))) {
    4307           6 :         std::swap(TVal, FVal);
    4308           6 :         std::swap(CTVal, CFVal);
    4309           6 :         CC = ISD::getSetCCInverse(CC, true);
    4310             :       }
    4311         182 :     } else if (CTVal && CFVal) {
    4312          58 :       const int64_t TrueVal = CTVal->getSExtValue();
    4313          58 :       const int64_t FalseVal = CFVal->getSExtValue();
    4314          29 :       bool Swap = false;
    4315             : 
    4316             :       // If both TVal and FVal are constants, see if FVal is the
    4317             :       // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
    4318             :       // instead of a CSEL in that case.
    4319          29 :       if (TrueVal == ~FalseVal) {
    4320             :         Opcode = AArch64ISD::CSINV;
    4321          27 :       } else if (TrueVal == -FalseVal) {
    4322             :         Opcode = AArch64ISD::CSNEG;
    4323          72 :       } else if (TVal.getValueType() == MVT::i32) {
    4324             :         // If our operands are only 32-bit wide, make sure we use 32-bit
    4325             :         // arithmetic for the check whether we can use CSINC. This ensures that
    4326             :         // the addition in the check will wrap around properly in case there is
    4327             :         // an overflow (which would not be the case if we do the check with
    4328             :         // 64-bit arithmetic).
    4329          18 :         const uint32_t TrueVal32 = CTVal->getZExtValue();
    4330          18 :         const uint32_t FalseVal32 = CFVal->getZExtValue();
    4331             : 
    4332           9 :         if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
    4333           2 :           Opcode = AArch64ISD::CSINC;
    4334             : 
    4335           2 :           if (TrueVal32 > FalseVal32) {
    4336             :             Swap = true;
    4337             :           }
    4338             :         }
    4339             :         // 64-bit check whether we can use CSINC.
    4340          28 :       } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
    4341           4 :         Opcode = AArch64ISD::CSINC;
    4342             : 
    4343           4 :         if (TrueVal > FalseVal) {
    4344             :           Swap = true;
    4345             :         }
    4346             :       }
    4347             : 
    4348             :       // Swap TVal and FVal if necessary.
    4349             :       if (Swap) {
    4350           3 :         std::swap(TVal, FVal);
    4351           3 :         std::swap(CTVal, CFVal);
    4352           3 :         CC = ISD::getSetCCInverse(CC, true);
    4353             :       }
    4354             : 
    4355          29 :       if (Opcode != AArch64ISD::CSEL) {
    4356             :         // Drop FVal since we can get its value by simply inverting/negating
    4357             :         // TVal.
    4358          11 :         FVal = TVal;
    4359             :       }
    4360             :     }
    4361             : 
    4362             :     // Avoid materializing a constant when possible by reusing a known value in
    4363             :     // a register.  However, don't perform this optimization if the known value
    4364             :     // is one, zero or negative one in the case of a CSEL.  We can always
    4365             :     // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
    4366             :     // FVal, respectively.
    4367         201 :     ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
    4368         401 :     if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
    4369         227 :         !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
    4370          21 :       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
    4371             :       // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
    4372             :       // "a != C ? x : a" to avoid materializing C.
    4373          21 :       if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
    4374           4 :         TVal = LHS;
    4375          17 :       else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
    4376           2 :         FVal = LHS;
    4377         183 :     } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
    4378             :       assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
    4379             :       // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
    4380             :       // avoid materializing C.
    4381           1 :       AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
    4382           1 :       if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
    4383           1 :         Opcode = AArch64ISD::CSINV;
    4384           1 :         TVal = LHS;
    4385           2 :         FVal = DAG.getConstant(0, dl, FVal.getValueType());
    4386             :       }
    4387             :     }
    4388             : 
    4389         201 :     SDValue CCVal;
    4390         201 :     SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
    4391         402 :     EVT VT = TVal.getValueType();
    4392         201 :     return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
    4393             :   }
    4394             : 
    4395             :   // Now we know we're dealing with FP values.
    4396             :   assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
    4397             :          LHS.getValueType() == MVT::f64);
    4398             :   assert(LHS.getValueType() == RHS.getValueType());
    4399         544 :   EVT VT = TVal.getValueType();
    4400         272 :   SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
    4401             : 
    4402             :   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
    4403             :   // clean.  Some of them require two CSELs to implement.
    4404             :   AArch64CC::CondCode CC1, CC2;
    4405         272 :   changeFPCCToAArch64CC(CC, CC1, CC2);
    4406             : 
    4407         272 :   if (DAG.getTarget().Options.UnsafeFPMath) {
    4408             :     // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
    4409             :     // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
    4410          11 :     ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
    4411          11 :     if (RHSVal && RHSVal->isZero()) {
    4412          11 :       ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
    4413          11 :       ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
    4414             : 
    4415          17 :       if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
    4416          26 :           CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
    4417             :         TVal = LHS;
    4418          12 :       else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
    4419          11 :                CFVal && CFVal->isZero() &&
    4420          12 :                FVal.getValueType() == LHS.getValueType())
    4421           4 :         FVal = LHS;
    4422             :     }
    4423             :   }
    4424             : 
    4425             :   // Emit first, and possibly only, CSEL.
    4426         272 :   SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
    4427         272 :   SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
    4428             : 
    4429             :   // If we need a second CSEL, emit it, using the output of the first as the
    4430             :   // RHS.  We're effectively OR'ing the two CC's together.
    4431         272 :   if (CC2 != AArch64CC::AL) {
    4432          42 :     SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
    4433          42 :     return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
    4434             :   }
    4435             : 
    4436             :   // Otherwise, return the output of the first CSEL.
    4437         230 :   return CS1;
    4438             : }
    4439             : 
    4440         193 : SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
    4441             :                                               SelectionDAG &DAG) const {
    4442         579 :   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
    4443         386 :   SDValue LHS = Op.getOperand(0);
    4444         386 :   SDValue RHS = Op.getOperand(1);
    4445         386 :   SDValue TVal = Op.getOperand(2);
    4446         386 :   SDValue FVal = Op.getOperand(3);
    4447         386 :   SDLoc DL(Op);
    4448         386 :   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
    4449             : }
    4450             : 
    4451         293 : SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
    4452             :                                            SelectionDAG &DAG) const {
    4453         586 :   SDValue CCVal = Op->getOperand(0);
    4454         586 :   SDValue TVal = Op->getOperand(1);
    4455         586 :   SDValue FVal = Op->getOperand(2);
    4456         586 :   SDLoc DL(Op);
    4457             : 
    4458         586 :   unsigned Opc = CCVal.getOpcode();
    4459             :   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
    4460             :   // instruction.
    4461         306 :   if (CCVal.getResNo() == 1 &&
    4462             :       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
    4463          13 :        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
    4464             :     // Only lower legal XALUO ops.
    4465          39 :     if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
    4466           0 :       return SDValue();
    4467             : 
    4468             :     AArch64CC::CondCode OFCC;
    4469             :     SDValue Value, Overflow;
    4470          52 :     std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
    4471          13 :     SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
    4472             : 
    4473             :     return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
    4474          26 :                        CCVal, Overflow);
    4475             :   }
    4476             : 
    4477             :   // Lower it the same way as we would lower a SELECT_CC node.
    4478             :   ISD::CondCode CC;
    4479         280 :   SDValue LHS, RHS;
    4480         560 :   if (CCVal.getOpcode() == ISD::SETCC) {
    4481         448 :     LHS = CCVal.getOperand(0);
    4482         448 :     RHS = CCVal.getOperand(1);
    4483         672 :     CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
    4484             :   } else {
    4485          56 :     LHS = CCVal;
    4486         112 :     RHS = DAG.getConstant(0, DL, CCVal.getValueType());
    4487          56 :     CC = ISD::SETNE;
    4488             :   }
    4489         280 :   return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
    4490             : }
    4491             : 
    4492          25 : SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
    4493             :                                               SelectionDAG &DAG) const {
    4494             :   // Jump table entries as PC relative offsets. No additional tweaking
    4495             :   // is necessary here. Just get the address of the jump table.
    4496          25 :   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
    4497             : 
    4498          26 :   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
    4499           2 :       !Subtarget->isTargetMachO()) {
    4500           1 :     return getAddrLarge(JT, DAG);
    4501             :   }
    4502          24 :   return getAddr(JT, DAG);
    4503             : }
    4504             : 
    4505         126 : SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
    4506             :                                                  SelectionDAG &DAG) const {
    4507         126 :   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
    4508             : 
    4509         126 :   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
    4510             :     // Use the GOT for the large code model on iOS.
    4511           8 :     if (Subtarget->isTargetMachO()) {
    4512           0 :       return getGOT(CP, DAG);
    4513             :     }
    4514           4 :     return getAddrLarge(CP, DAG);
    4515             :   } else {
    4516         122 :     return getAddr(CP, DAG);
    4517             :   }
    4518             : }
    4519             : 
    4520           6 : SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
    4521             :                                                SelectionDAG &DAG) const {
    4522           6 :   BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
    4523           8 :   if (getTargetMachine().getCodeModel() == CodeModel::Large &&
    4524           4 :       !Subtarget->isTargetMachO()) {
    4525           2 :     return getAddrLarge(BA, DAG);
    4526             :   } else {
    4527           4 :     return getAddr(BA, DAG);
    4528             :   }
    4529             : }
    4530             : 
    4531           8 : SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
    4532             :                                                  SelectionDAG &DAG) const {
    4533             :   AArch64FunctionInfo *FuncInfo =
    4534          16 :       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
    4535             : 
    4536          16 :   SDLoc DL(Op);
    4537             :   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
    4538          32 :                                  getPointerTy(DAG.getDataLayout()));
    4539          24 :   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
    4540          24 :   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
    4541          32 :                       MachinePointerInfo(SV));
    4542             : }
    4543             : 
    4544          12 : SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
    4545             :                                                   SelectionDAG &DAG) const {
    4546             :   AArch64FunctionInfo *FuncInfo =
    4547          24 :       DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
    4548             : 
    4549          24 :   SDLoc DL(Op);
    4550             :   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
    4551             :                                      ? FuncInfo->getVarArgsGPRIndex()
    4552             :                                      : FuncInfo->getVarArgsStackIndex(),
    4553          48 :                                  getPointerTy(DAG.getDataLayout()));
    4554          36 :   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
    4555          36 :   return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
    4556          48 :                       MachinePointerInfo(SV));
    4557             : }
    4558             : 
    4559           5 : SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
    4560             :                                                 SelectionDAG &DAG) const {
    4561             :   // The layout of the va_list struct is specified in the AArch64 Procedure Call
    4562             :   // Standard, section B.3.
    4563           5 :   MachineFunction &MF = DAG.getMachineFunction();
    4564           5 :   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
    4565          15 :   auto PtrVT = getPointerTy(DAG.getDataLayout());
    4566          10 :   SDLoc DL(Op);
    4567             : 
    4568          10 :   SDValue Chain = Op.getOperand(0);
    4569          10 :   SDValue VAList = Op.getOperand(1);
    4570          15 :   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
    4571          10 :   SmallVector<SDValue, 4> MemOps;
    4572             : 
    4573             :   // void *__stack at offset 0
    4574           5 :   SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
    4575           5 :   MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
    4576          15 :                                 MachinePointerInfo(SV), /* Alignment = */ 8));
    4577             : 
    4578             :   // void *__gr_top at offset 8
    4579           5 :   int GPRSize = FuncInfo->getVarArgsGPRSize();
    4580           5 :   if (GPRSize > 0) {
    4581           3 :     SDValue GRTop, GRTopAddr;
    4582             : 
    4583           3 :     GRTopAddr =
    4584          12 :         DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
    4585             : 
    4586           3 :     GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
    4587           3 :     GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
    4588          12 :                         DAG.getConstant(GPRSize, DL, PtrVT));
    4589             : 
    4590           3 :     MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
    4591             :                                   MachinePointerInfo(SV, 8),
    4592           9 :                                   /* Alignment = */ 8));
    4593             :   }
    4594             : 
    4595             :   // void *__vr_top at offset 16
    4596           5 :   int FPRSize = FuncInfo->getVarArgsFPRSize();
    4597           5 :   if (FPRSize > 0) {
    4598           4 :     SDValue VRTop, VRTopAddr;
    4599           4 :     VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
    4600          16 :                             DAG.getConstant(16, DL, PtrVT));
    4601             : 
    4602           4 :     VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
    4603           4 :     VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
    4604          16 :                         DAG.getConstant(FPRSize, DL, PtrVT));
    4605             : 
    4606           4 :     MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
    4607             :                                   MachinePointerInfo(SV, 16),
    4608          12 :                                   /* Alignment = */ 8));
    4609             :   }
    4610             : 
    4611             :   // int __gr_offs at offset 24
    4612             :   SDValue GROffsAddr =
    4613          15 :       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
    4614           5 :   MemOps.push_back(DAG.getStore(
    4615           5 :       Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
    4616          20 :       MachinePointerInfo(SV, 24), /* Alignment = */ 4));
    4617             : 
    4618             :   // int __vr_offs at offset 28
    4619             :   SDValue VROffsAddr =
    4620          15 :       DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
    4621           5 :   MemOps.push_back(DAG.getStore(
    4622           5 :       Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
    4623          20 :       MachinePointerInfo(SV, 28), /* Alignment = */ 4));
    4624             : 
    4625          20 :   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
    4626             : }
    4627             : 
    4628          25 : SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
    4629             :                                             SelectionDAG &DAG) const {
    4630          25 :   MachineFunction &MF = DAG.getMachineFunction();
    4631             : 
    4632          71 :   if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
    4633          12 :     return LowerWin64_VASTART(Op, DAG);
    4634          18 :   else if (Subtarget->isTargetDarwin())
    4635           8 :     return LowerDarwin_VASTART(Op, DAG);
    4636             :   else
    4637           5 :     return LowerAAPCS_VASTART(Op, DAG);
    4638             : }
    4639             : 
    4640           2 : SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
    4641             :                                            SelectionDAG &DAG) const {
    4642             :   // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
    4643             :   // pointer.
    4644           4 :   SDLoc DL(Op);
    4645             :   unsigned VaListSize =
    4646           6 :       Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
    4647           6 :   const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
    4648           6 :   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
    4649             : 
    4650           6 :   return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
    4651           4 :                        Op.getOperand(2),
    4652           2 :                        DAG.getConstant(VaListSize, DL, MVT::i32),
    4653             :                        8, false, false, false, MachinePointerInfo(DestSV),
    4654          10 :                        MachinePointerInfo(SrcSV));
    4655             : }
    4656             : 
    4657          16 : SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
    4658             :   assert(Subtarget->isTargetDarwin() &&
    4659             :          "automatic va_arg instruction only works on Darwin");
    4660             : 
    4661          48 :   const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
    4662          32 :   EVT VT = Op.getValueType();
    4663          32 :   SDLoc DL(Op);
    4664          32 :   SDValue Chain = Op.getOperand(0);
    4665          32 :   SDValue Addr = Op.getOperand(1);
    4666          32 :   unsigned Align = Op.getConstantOperandVal(3);
    4667          48 :   auto PtrVT = getPointerTy(DAG.getDataLayout());
    4668             : 
    4669          48 :   SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
    4670          32 :   Chain = VAList.getValue(1);
    4671             : 
    4672          16 :   if (Align > 8) {
    4673             :     assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
    4674           1 :     VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
    4675           4 :                          DAG.getConstant(Align - 1, DL, PtrVT));
    4676           1 :     VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
    4677           4 :                          DAG.getConstant(-(int64_t)Align, DL, PtrVT));
    4678             :   }
    4679             : 
    4680          16 :   Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
    4681          32 :   uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
    4682             : 
    4683             :   // Scalar integer and FP values smaller than 64 bits are implicitly extended
    4684             :   // up to 64 bits.  At the very least, we have to increase the striding of the
    4685             :   // vaargs list to match this, and for FP values we need to introduce
    4686             :   // FP_ROUND nodes as well.
    4687          31 :   if (VT.isInteger() && !VT.isVector())
    4688             :     ArgSize = 8;
    4689          16 :   bool NeedFPTrunc = false;
    4690          18 :   if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
    4691             :     ArgSize = 8;
    4692             :     NeedFPTrunc = true;
    4693             :   }
    4694             : 
    4695             :   // Increment the pointer, VAList, to the next vaarg
    4696             :   SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
    4697          48 :                                DAG.getConstant(ArgSize, DL, PtrVT));
    4698             :   // Store the incremented VAList to the legalized pointer
    4699             :   SDValue APStore =
    4700          32 :       DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
    4701             : 
    4702             :   // Load the actual argument out of the pointer VAList
    4703          16 :   if (NeedFPTrunc) {
    4704             :     // Load the value as an f64.
    4705             :     SDValue WideFP =
    4706           3 :         DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
    4707             :     // Round the value down to an f32.
    4708             :     SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
    4709           2 :                                    DAG.getIntPtrConstant(1, DL));
    4710           2 :     SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
    4711             :     // Merge the rounded value with the chain output of the load.
    4712           1 :     return DAG.getMergeValues(Ops, DL);
    4713             :   }
    4714             : 
    4715          30 :   return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
    4716             : }
    4717             : 
    4718           4 : SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
    4719             :                                               SelectionDAG &DAG) const {
    4720           4 :   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
    4721           4 :   MFI.setFrameAddressIsTaken(true);
    4722             : 
    4723           8 :   EVT VT = Op.getValueType();
    4724           8 :   SDLoc DL(Op);
    4725          16 :   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
    4726             :   SDValue FrameAddr =
    4727           4 :       DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
    4728          16 :   while (Depth--)
    4729           6 :     FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
    4730          24 :                             MachinePointerInfo());
    4731           8 :   return FrameAddr;
    4732             : }
    4733             : 
    4734             : // FIXME? Maybe this could be a TableGen attribute on some registers and
    4735             : // this table could be generated automatically from RegInfo.
    4736          12 : unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
    4737             :                                                   SelectionDAG &DAG) const {
    4738          12 :   unsigned Reg = StringSwitch<unsigned>(RegName)
    4739          36 :                        .Case("sp", AArch64::SP)
    4740          36 :                        .Case("x18", AArch64::X18)
    4741          36 :                        .Case("w18", AArch64::W18)
    4742          24 :                        .Default(0);
    4743          16 :   if ((Reg == AArch64::X18 || Reg == AArch64::W18) &&
    4744           4 :       !Subtarget->isX18Reserved())
    4745             :     Reg = 0;
    4746          10 :   if (Reg)
    4747           6 :     return Reg;
    4748           6 :   report_fatal_error(Twine("Invalid register name \""
    4749          18 :                               + StringRef(RegName)  + "\"."));
    4750             : }
    4751             : 
    4752           6 : SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
    4753             :                                                SelectionDAG &DAG) const {
    4754           6 :   MachineFunction &MF = DAG.getMachineFunction();
    4755           6 :   MachineFrameInfo &MFI = MF.getFrameInfo();
    4756           6 :   MFI.setReturnAddressIsTaken(true);
    4757             : 
    4758          12 :   EVT VT = Op.getValueType();
    4759          12 :   SDLoc DL(Op);
    4760          24 :   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
    4761           6 :   if (Depth) {
    4762           2 :     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
    4763           8 :     SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
    4764             :     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
    4765             :                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
    4766           8 :                        MachinePointerInfo());
    4767             :   }
    4768             : 
    4769             :   // Return LR, which contains the return address. Mark it an implicit live-in.
    4770           4 :   unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
    4771           4 :   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
    4772             : }
    4773             : 
    4774             : /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
    4775             : /// i64 values and take a 2 x i64 value to shift plus a shift amount.
    4776           2 : SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
    4777             :                                                     SelectionDAG &DAG) const {
    4778             :   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
    4779           4 :   EVT VT = Op.getValueType();
    4780           2 :   unsigned VTBits = VT.getSizeInBits();
    4781           4 :   SDLoc dl(Op);
    4782           4 :   SDValue ShOpLo = Op.getOperand(0);
    4783           4 :   SDValue ShOpHi = Op.getOperand(1);
    4784           4 :   SDValue ShAmt = Op.getOperand(2);
    4785           4 :   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
    4786             : 
    4787             :   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
    4788             : 
    4789             :   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
    4790           6 :                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
    4791           2 :   SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
    4792             : 
    4793             :   // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
    4794             :   // is "undef". We wanted 0, so CSEL it directly.
    4795           2 :   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
    4796           2 :                                ISD::SETEQ, dl, DAG);
    4797           2 :   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
    4798           2 :   HiBitsForLo =
    4799           6 :       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
    4800           4 :                   HiBitsForLo, CCVal, Cmp);
    4801             : 
    4802             :   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
    4803           6 :                                    DAG.getConstant(VTBits, dl, MVT::i64));
    4804             : 
    4805           2 :   SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
    4806             :   SDValue LoForNormalShift =
    4807           2 :       DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
    4808             : 
    4809           4 :   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
    4810           4 :                        dl, DAG);
    4811           2 :   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
    4812           2 :   SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
    4813             :   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
    4814           2 :                            LoForNormalShift, CCVal, Cmp);
    4815             : 
    4816             :   // AArch64 shifts larger than the register width are wrapped rather than
    4817             :   // clamped, so we can't just emit "hi >> x".
    4818           2 :   SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
    4819             :   SDValue HiForBigShift =
    4820             :       Opc == ISD::SRA
    4821             :           ? DAG.getNode(Opc, dl, VT, ShOpHi,
    4822           4 :                         DAG.getConstant(VTBits - 1, dl, MVT::i64))
    4823           3 :           : DAG.getConstant(0, dl, VT);
    4824             :   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
    4825           2 :                            HiForNormalShift, CCVal, Cmp);
    4826             : 
    4827           2 :   SDValue Ops[2] = { Lo, Hi };
    4828           4 :   return DAG.getMergeValues(Ops, dl);
    4829             : }
    4830             : 
    4831             : /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
    4832             : /// i64 values and take a 2 x i64 value to shift plus a shift amount.
    4833           1 : SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
    4834             :                                                    SelectionDAG &DAG) const {
    4835             :   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
    4836           2 :   EVT VT = Op.getValueType();
    4837           1 :   unsigned VTBits = VT.getSizeInBits();
    4838           2 :   SDLoc dl(Op);
    4839           2 :   SDValue ShOpLo = Op.getOperand(0);
    4840           2 :   SDValue ShOpHi = Op.getOperand(1);
    4841           2 :   SDValue ShAmt = Op.getOperand(2);
    4842             : 
    4843             :   assert(Op.getOpcode() == ISD::SHL_PARTS);
    4844             :   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
    4845           3 :                                  DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
    4846           1 :   SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
    4847             : 
    4848             :   // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
    4849             :   // is "undef". We wanted 0, so CSEL it directly.
    4850           1 :   SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
    4851           1 :                                ISD::SETEQ, dl, DAG);
    4852           1 :   SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
    4853           1 :   LoBitsForHi =
    4854           3 :       DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
    4855           2 :                   LoBitsForHi, CCVal, Cmp);
    4856             : 
    4857             :   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
    4858           3 :                                    DAG.getConstant(VTBits, dl, MVT::i64));
    4859           1 :   SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
    4860             :   SDValue HiForNormalShift =
    4861           1 :       DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
    4862             : 
    4863           1 :   SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
    4864             : 
    4865           2 :   Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
    4866           2 :                        dl, DAG);
    4867           1 :   CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
    4868             :   SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
    4869           1 :                            HiForNormalShift, CCVal, Cmp);
    4870             : 
    4871             :   // AArch64 shifts of larger than register sizes are wrapped rather than
    4872             :   // clamped, so we can't just emit "lo << a" if a is too big.
    4873           1 :   SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
    4874           1 :   SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
    4875             :   SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
    4876           1 :                            LoForNormalShift, CCVal, Cmp);
    4877             : 
    4878           1 :   SDValue Ops[2] = { Lo, Hi };
    4879           2 :   return DAG.getMergeValues(Ops, dl);
    4880             : }
    4881             : 
    4882         939 : bool AArch64TargetLowering::isOffsetFoldingLegal(
    4883             :     const GlobalAddressSDNode *GA) const {
    4884             :   DEBUG(dbgs() << "Skipping offset folding global address: ");
    4885             :   DEBUG(GA->dump());
    4886             :   DEBUG(dbgs() << "AArch64 doesn't support folding offsets into global "
    4887             :         "addresses\n");
    4888         939 :   return false;
    4889             : }
    4890             : 
    4891         533 : bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
    4892             :   // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
    4893             :   // FIXME: We should be able to handle f128 as well with a clever lowering.
    4894         955 :   if (Imm.isPosZero() && (VT == MVT::f16 || VT == MVT::f64 || VT == MVT::f32)) {
    4895             :     DEBUG(dbgs() << "Legal fp imm: materialize 0 using the zero register\n");
    4896             :     return true;
    4897             :   }
    4898             : 
    4899         370 :   StringRef FPType;
    4900         370 :   bool IsLegal = false;
    4901         370 :   SmallString<128> ImmStrVal;
    4902         370 :   Imm.toString(ImmStrVal);
    4903             : 
    4904         740 :   if (VT == MVT::f64) {
    4905         115 :     FPType = "f64";
    4906         115 :     IsLegal = AArch64_AM::getFP64Imm(Imm) != -1;
    4907         510 :   } else if (VT == MVT::f32) {
    4908         215 :     FPType = "f32";
    4909         215 :     IsLegal = AArch64_AM::getFP32Imm(Imm) != -1;
    4910          70 :   } else if (VT == MVT::f16 && Subtarget->hasFullFP16()) {
    4911          22 :     FPType = "f16";
    4912          22 :     IsLegal = AArch64_AM::getFP16Imm(Imm) != -1;
    4913             :   }
    4914             : 
    4915         352 :   if (IsLegal) {
    4916             :     DEBUG(dbgs() << "Legal " << FPType << " imm value: " << ImmStrVal << "\n");
    4917             :     return true;
    4918             :   }
    4919             : 
    4920         105 :   if (!FPType.empty())
    4921             :     DEBUG(dbgs() << "Illegal " << FPType << " imm value: " << ImmStrVal << "\n");
    4922             :   else
    4923             :     DEBUG(dbgs() << "Illegal fp imm " << ImmStrVal << ": unsupported fp type\n");
    4924             : 
    4925         105 :   return false;
    4926             : }
    4927             : 
    4928             : //===----------------------------------------------------------------------===//
    4929             : //                          AArch64 Optimization Hooks
    4930             : //===----------------------------------------------------------------------===//
    4931             : 
    4932          35 : static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
    4933             :                            SDValue Operand, SelectionDAG &DAG,
    4934             :                            int &ExtraSteps) {
    4935          70 :   EVT VT = Operand.getValueType();
    4936          35 :   if (ST->hasNEON() &&
    4937          99 :       (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
    4938          43 :        VT == MVT::f32 || VT == MVT::v1f32 ||
    4939          37 :        VT == MVT::v2f32 || VT == MVT::v4f32)) {
    4940          27 :     if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
    4941             :       // For the reciprocal estimates, convergence is quadratic, so the number
    4942             :       // of digits is doubled after each iteration.  In ARMv8, the accuracy of
    4943             :       // the initial estimate is 2^-8.  Thus the number of extra steps to refine
    4944             :       // the result for float (23 mantissa bits) is 2 and for double (52
    4945             :       // mantissa bits) is 3.
    4946          54 :       ExtraSteps = VT == MVT::f64 ? 3 : 2;
    4947             : 
    4948          81 :     return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
    4949             :   }
    4950             : 
    4951           8 :   return SDValue();
    4952             : }
    4953             : 
    4954          57 : SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
    4955             :                                                SelectionDAG &DAG, int Enabled,
    4956             :                                                int &ExtraSteps,
    4957             :                                                bool &UseOneConst,
    4958             :                                                bool Reciprocal) const {
    4959          57 :   if (Enabled == ReciprocalEstimate::Enabled ||
    4960          57 :       (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
    4961          48 :     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
    4962          24 :                                        DAG, ExtraSteps)) {
    4963          36 :       SDLoc DL(Operand);
    4964          36 :       EVT VT = Operand.getValueType();
    4965             : 
    4966          18 :       SDNodeFlags Flags;
    4967          18 :       Flags.setUnsafeAlgebra(true);
    4968             : 
    4969             :       // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
    4970             :       // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
    4971          56 :       for (int i = ExtraSteps; i > 0; --i) {
    4972             :         SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
    4973          38 :                                    Flags);
    4974          38 :         Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
    4975          38 :         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
    4976             :       }
    4977             : 
    4978          18 :       if (!Reciprocal) {
    4979           9 :         EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
    4980          27 :                                       VT);
    4981           9 :         SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
    4982           9 :         SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
    4983             : 
    4984           9 :         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
    4985             :         // Correct the result if the operand is 0.0.
    4986          18 :         Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
    4987           9 :                                VT, Eq, Operand, Estimate);
    4988             :       }
    4989             : 
    4990          18 :       ExtraSteps = 0;
    4991          18 :       return Estimate;
    4992             :     }
    4993             : 
    4994          39 :   return SDValue();
    4995             : }
    4996             : 
    4997          56 : SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
    4998             :                                                 SelectionDAG &DAG, int Enabled,
    4999             :                                                 int &ExtraSteps) const {
    5000          56 :   if (Enabled == ReciprocalEstimate::Enabled)
    5001          22 :     if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
    5002          11 :                                        DAG, ExtraSteps)) {
    5003          18 :       SDLoc DL(Operand);
    5004          18 :       EVT VT = Operand.getValueType();
    5005             : 
    5006           9 :       SDNodeFlags Flags;
    5007           9 :       Flags.setUnsafeAlgebra(true);
    5008             : 
    5009             :       // Newton reciprocal iteration: E * (2 - X * E)
    5010             :       // AArch64 reciprocal iteration instruction: (2 - M * N)
    5011          28 :       for (int i = ExtraSteps; i > 0; --i) {
    5012             :         SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
    5013          19 :                                    Estimate, Flags);
    5014          19 :         Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
    5015             :       }
    5016             : 
    5017           9 :       ExtraSteps = 0;
    5018           9 :       return Estimate;
    5019             :     }
    5020             : 
    5021          47 :   return SDValue();
    5022             : }
    5023             : 
    5024             : //===----------------------------------------------------------------------===//
    5025             : //                          AArch64 Inline Assembly Support
    5026             : //===----------------------------------------------------------------------===//
    5027             : 
    5028             : // Table of Constraints
    5029             : // TODO: This is the current set of constraints supported by ARM for the
    5030             : // compiler, not all of them may make sense, e.g. S may be difficult to support.
    5031             : //
    5032             : // r - A general register
    5033             : // w - An FP/SIMD register of some size in the range v0-v31
    5034             : // x - An FP/SIMD register of some size in the range v0-v15
    5035             : // I - Constant that can be used with an ADD instruction
    5036             : // J - Constant that can be used with a SUB instruction
    5037             : // K - Constant that can be used with a 32-bit logical instruction
    5038             : // L - Constant that can be used with a 64-bit logical instruction
    5039             : // M - Constant that can be used as a 32-bit MOV immediate
    5040             : // N - Constant that can be used as a 64-bit MOV immediate
    5041             : // Q - A memory reference with base register and no offset
    5042             : // S - A symbolic address
    5043             : // Y - Floating point constant zero
    5044             : // Z - Integer constant zero
    5045             : //
    5046             : //   Note that general register operands will be output using their 64-bit x
    5047             : // register name, whatever the size of the variable, unless the asm operand
    5048             : // is prefixed by the %w modifier. Floating-point and SIMD register operands
    5049             : // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
    5050             : // %q modifier.
    5051          22 : const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
    5052             :   // At this point, we have to lower this constraint to something else, so we
    5053             :   // lower it to an "r" or "w". However, by doing this we will force the result
    5054             :   // to be in register, while the X constraint is much more permissive.
    5055             :   //
    5056             :   // Although we are correct (we are free to emit anything, without
    5057             :   // constraints), we might break use cases that would expect us to be more
    5058             :   // efficient and emit something else.
    5059          22 :   if (!Subtarget->hasFPARMv8())
    5060             :     return "r";
    5061             : 
    5062          19 :   if (ConstraintVT.isFloatingPoint())
    5063             :     return "w";
    5064             : 
    5065          20 :   if (ConstraintVT.isVector() &&
    5066           4 :      (ConstraintVT.getSizeInBits() == 64 ||
    5067             :       ConstraintVT.getSizeInBits() == 128))
    5068             :     return "w";
    5069             : 
    5070             :   return "r";
    5071             : }
    5072             : 
    5073             : /// getConstraintType - Given a constraint letter, return the type of
    5074             : /// constraint it is for this target.
    5075             : AArch64TargetLowering::ConstraintType
    5076       13315 : AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
    5077       13315 :   if (Constraint.size() == 1) {
    5078        1102 :     switch (Constraint[0]) {
    5079             :     default:
    5080             :       break;
    5081             :     case 'z':
    5082             :       return C_Other;
    5083          68 :     case 'x':
    5084             :     case 'w':
    5085          68 :       return C_RegisterClass;
    5086             :     // An address with a single base register. Due to the way we
    5087             :     // currently handle addresses it is the same as 'r'.
    5088           6 :     case 'Q':
    5089           6 :       return C_Memory;
    5090             :     }
    5091             :   }
    5092       13209 :   return TargetLowering::getConstraintType(Constraint);
    5093             : }
    5094             : 
    5095             : /// Examine constraint type and operand type and determine a weight value.
    5096             : /// This object must already have been set up with the operand type
    5097             : /// and the current alternative constraint selected.
    5098             : TargetLowering::ConstraintWeight
    5099           0 : AArch64TargetLowering::getSingleConstraintMatchWeight(
    5100             :     AsmOperandInfo &info, const char *constraint) const {
    5101           0 :   ConstraintWeight weight = CW_Invalid;
    5102           0 :   Value *CallOperandVal = info.CallOperandVal;
    5103             :   // If we don't have a value, we can't do a match,
    5104             :   // but allow it at the lowest weight.
    5105           0 :   if (!CallOperandVal)
    5106             :     return CW_Default;
    5107           0 :   Type *type = CallOperandVal->getType();
    5108             :   // Look at the constraint type.
    5109           0 :   switch (*constraint) {
    5110           0 :   default:
    5111           0 :     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
    5112           0 :     break;
    5113           0 :   case 'x':
    5114             :   case 'w':
    5115           0 :     if (type->isFloatingPointTy() || type->isVectorTy())
    5116             :       weight = CW_Register;
    5117             :     break;
    5118             :   case 'z':
    5119             :     weight = CW_Constant;
    5120             :     break;
    5121             :   }
    5122             :   return weight;
    5123             : }
    5124             : 
    5125             : std::pair<unsigned, const TargetRegisterClass *>
    5126        5098 : AArch64TargetLowering::getRegForInlineAsmConstraint(
    5127             :     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
    5128        5098 :   if (Constraint.size() == 1) {
    5129         154 :     switch (Constraint[0]) {
    5130          61 :     case 'r':
    5131          61 :       if (VT.getSizeInBits() == 64)
    5132          21 :         return std::make_pair(0U, &AArch64::GPR64commonRegClass);
    5133          40 :       return std::make_pair(0U, &AArch64::GPR32commonRegClass);
    5134          15 :     case 'w':
    5135          15 :       if (VT.getSizeInBits() == 16)
    5136           3 :         return std::make_pair(0U, &AArch64::FPR16RegClass);
    5137          12 :       if (VT.getSizeInBits() == 32)
    5138           2 :         return std::make_pair(0U, &AArch64::FPR32RegClass);
    5139          10 :       if (VT.getSizeInBits() == 64)
    5140           8 :         return std::make_pair(0U, &AArch64::FPR64RegClass);
    5141           2 :       if (VT.getSizeInBits() == 128)
    5142           2 :         return std::make_pair(0U, &AArch64::FPR128RegClass);
    5143             :       break;
    5144             :     // The instructions that this constraint is designed for can
    5145             :     // only take 128-bit registers so just use that regclass.
    5146           1 :     case 'x':
    5147           1 :       if (VT.getSizeInBits() == 128)
    5148           1 :         return std::make_pair(0U, &AArch64::FPR128_loRegClass);
    5149             :       break;
    5150             :     }
    5151             :   }
    5152       10042 :   if (StringRef("{cc}").equals_lower(Constraint))
    5153           0 :     return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
    5154             : 
    5155             :   // Use the default implementation in TargetLowering to convert the register
    5156             :   // constraint into a member of a register class.
    5157        5021 :   std::pair<unsigned, const TargetRegisterClass *> Res;
    5158       10042 :   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
    5159             : 
    5160             :   // Not found as a standard register?
    5161        5021 :   if (!Res.second) {
    5162         895 :     unsigned Size = Constraint.size();
    5163        3475 :     if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
    5164        4283 :         tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
    5165             :       int RegNo;
    5166        2502 :       bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
    5167         834 :       if (!Failed && RegNo >= 0 && RegNo <= 31) {
    5168             :         // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
    5169             :         // By default we'll emit v0-v31 for this unless there's a modifier where
    5170             :         // we'll emit the correct register as well.
    5171        1668 :         if (VT != MVT::Other && VT.getSizeInBits() == 64) {
    5172           2 :           Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
    5173           1 :           Res.second = &AArch64::FPR64RegClass;
    5174             :         } else {
    5175        1666 :           Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
    5176         833 :           Res.second = &AArch64::FPR128RegClass;
    5177             :         }
    5178             :       }
    5179             :     }
    5180             :   }
    5181             : 
    5182        5021 :   return Res;
    5183             : }
    5184             : 
    5185             : /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
    5186             : /// vector.  If it is invalid, don't add anything to Ops.
    5187          52 : void AArch64TargetLowering::LowerAsmOperandForConstraint(
    5188             :     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
    5189             :     SelectionDAG &DAG) const {
    5190          52 :   SDValue Result;
    5191             : 
    5192             :   // Currently only support length 1 constraints.
    5193          52 :   if (Constraint.length() != 1)
    5194             :     return;
    5195             : 
    5196          52 :   char ConstraintLetter = Constraint[0];
    5197          52 :   switch (ConstraintLetter) {
    5198             :   default:
    5199             :     break;
    5200             : 
    5201             :   // This set of constraints deal with valid constants for various instructions.
    5202             :   // Validate and return a target constant for them if we can.
    5203           9 :   case 'z': {
    5204             :     // 'z' maps to xzr or wzr so it needs an input of 0.
    5205           9 :     if (!isNullConstant(Op))
    5206             :       return;
    5207             : 
    5208          21 :     if (Op.getValueType() == MVT::i64)
    5209           0 :       Result = DAG.getRegister(AArch64::XZR, MVT::i64);
    5210             :     else
    5211           7 :       Result = DAG.getRegister(AArch64::WZR, MVT::i32);
    5212             :     break;
    5213             :   }
    5214             : 
    5215          28 :   case 'I':
    5216             :   case 'J':
    5217             :   case 'K':
    5218             :   case 'L':
    5219             :   case 'M':
    5220             :   case 'N':
    5221          28 :     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
    5222             :     if (!C)
    5223             :       return;
    5224             : 
    5225             :     // Grab the value and do some validation.
    5226          28 :     uint64_t CVal = C->getZExtValue();
    5227          28 :     switch (ConstraintLetter) {
    5228             :     // The I constraint applies only to simple ADD or SUB immediate operands:
    5229             :     // i.e. 0 to 4095 with optional shift by 12
    5230             :     // The J constraint applies only to ADD or SUB immediates that would be
    5231             :     // valid when negated, i.e. if [an add pattern] were to be output as a SUB
    5232             :     // instruction [or vice versa], in other words -1 to -4095 with optional
    5233             :     // left shift by 12.
    5234           4 :     case 'I':
    5235           4 :       if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
    5236             :         break;
    5237             :       return;
    5238           5 :     case 'J': {
    5239           5 :       uint64_t NVal = -C->getSExtValue();
    5240           5 :       if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
    5241           4 :         CVal = C->getSExtValue();
    5242           4 :         break;
    5243             :       }
    5244             :       return;
    5245             :     }
    5246             :     // The K and L constraints apply *only* to logical immediates, including
    5247             :     // what used to be the MOVI alias for ORR (though the MOVI alias has now
    5248             :     // been removed and MOV should be used). So these constraints have to
    5249             :     // distinguish between bit patterns that are valid 32-bit or 64-bit
    5250             :     // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
    5251             :     // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
    5252             :     // versa.
    5253           4 :     case 'K':
    5254           4 :       if (AArch64_AM::isLogicalImmediate(CVal, 32))
    5255             :         break;
    5256             :       return;
    5257           3 :     case 'L':
    5258           3 :       if (AArch64_AM::isLogicalImmediate(CVal, 64))
    5259             :         break;
    5260             :       return;
    5261             :     // The M and N constraints are a superset of K and L respectively, for use
    5262             :     // with the MOV (immediate) alias. As well as the logical immediates they
    5263             :     // also match 32 or 64-bit immediates that can be loaded either using a
    5264             :     // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
    5265             :     // (M) or 64-bit 0x1234000000000000 (N) etc.
    5266             :     // As a note some of this code is liberally stolen from the asm parser.
    5267           6 :     case 'M': {
    5268           6 :       if (!isUInt<32>(CVal))
    5269             :         return;
    5270           6 :       if (AArch64_AM::isLogicalImmediate(CVal, 32))
    5271             :         break;
    5272           4 :       if ((CVal & 0xFFFF) == CVal)
    5273             :         break;
    5274           3 :       if ((CVal & 0xFFFF0000ULL) == CVal)
    5275             :         break;
    5276           2 :       uint64_t NCVal = ~(uint32_t)CVal;
    5277           2 :       if ((NCVal & 0xFFFFULL) == NCVal)
    5278             :         break;
    5279           1 :       if ((NCVal & 0xFFFF0000ULL) == NCVal)
    5280             :         break;
    5281             :       return;
    5282             :     }
    5283           6 :     case 'N': {
    5284           6 :       if (AArch64_AM::isLogicalImmediate(CVal, 64))
    5285             :         break;
    5286           5 :       if ((CVal & 0xFFFFULL) == CVal)
    5287             :         break;
    5288           3 :       if ((CVal & 0xFFFF0000ULL) == CVal)
    5289             :         break;
    5290           3 :       if ((CVal & 0xFFFF00000000ULL) == CVal)
    5291             :         break;
    5292           3 :       if ((CVal & 0xFFFF000000000000ULL) == CVal)
    5293             :         break;
    5294           2 :       uint64_t NCVal = ~CVal;
    5295           2 :       if ((NCVal & 0xFFFFULL) == NCVal)
    5296             :         break;
    5297           1 :       if ((NCVal & 0xFFFF0000ULL) == NCVal)
    5298             :         break;
    5299           1 :       if ((NCVal & 0xFFFF00000000ULL) == NCVal)
    5300             :         break;
    5301           1 :       if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
    5302             :         break;
    5303             :       return;
    5304             :     }
    5305             :     default:
    5306             :       return;
    5307          12 :     }
    5308             : 
    5309             :     // All assembler immediates are 64-bit integers.
    5310          72 :     Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
    5311          18 :     break;
    5312             :   }
    5313             : 
    5314          40 :   if (Result.getNode()) {
    5315          25 :     Ops.push_back(Result);
    5316          25 :     return;
    5317             :   }
    5318             : 
    5319          15 :   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
    5320             : }
    5321             : 
    5322             : //===----------------------------------------------------------------------===//
    5323             : //                     AArch64 Advanced SIMD Support
    5324             : //===----------------------------------------------------------------------===//
    5325             : 
    5326             : /// WidenVector - Given a value in the V64 register class, produce the
    5327             : /// equivalent value in the V128 register class.
    5328        1406 : static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
    5329        2812 :   EVT VT = V64Reg.getValueType();
    5330        1406 :   unsigned NarrowSize = VT.getVectorNumElements();
    5331        1406 :   MVT EltTy = VT.getVectorElementType().getSimpleVT();
    5332        1406 :   MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
    5333        2812 :   SDLoc DL(V64Reg);
    5334             : 
    5335             :   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
    5336        5624 :                      V64Reg, DAG.getConstant(0, DL, MVT::i32));
    5337             : }
    5338             : 
    5339             : /// getExtFactor - Determine the adjustment factor for the position when
    5340             : /// generating an "extract from vector registers" instruction.
    5341          93 : static unsigned getExtFactor(SDValue &V) {
    5342         186 :   EVT EltType = V.getValueType().getVectorElementType();
    5343          93 :   return EltType.getSizeInBits() / 8;
    5344             : }
    5345             : 
    5346             : /// NarrowVector - Given a value in the V128 register class, produce the
    5347             : /// equivalent value in the V64 register class.
    5348         289 : static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
    5349         578 :   EVT VT = V128Reg.getValueType();
    5350         289 :   unsigned WideSize = VT.getVectorNumElements();
    5351         289 :   MVT EltTy = VT.getVectorElementType().getSimpleVT();
    5352         289 :   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
    5353         578 :   SDLoc DL(V128Reg);
    5354             : 
    5355         578 :   return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
    5356             : }
    5357             : 
    5358             : // Gather data to see if the operation can be modelled as a
    5359             : // shuffle in combination with VEXTs.
    5360         124 : SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
    5361             :                                                   SelectionDAG &DAG) const {
    5362             :   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
    5363             :   DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
    5364         248 :   SDLoc dl(Op);
    5365         248 :   EVT VT = Op.getValueType();
    5366         124 :   unsigned NumElts = VT.getVectorNumElements();
    5367             : 
    5368             :   struct ShuffleSourceInfo {
    5369             :     SDValue Vec;
    5370             :     unsigned MinElt;
    5371             :     unsigned MaxElt;
    5372             : 
    5373             :     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
    5374             :     // be compatible with the shuffle we intend to construct. As a result
    5375             :     // ShuffleVec will be some sliding window into the original Vec.
    5376             :     SDValue ShuffleVec;
    5377             : 
    5378             :     // Code should guarantee that element i in Vec starts at element "WindowBase
    5379             :     // + i * WindowScale in ShuffleVec".
    5380             :     int WindowBase;
    5381             :     int WindowScale;
    5382             : 
    5383             :     ShuffleSourceInfo(SDValue Vec)
    5384           7 :       : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
    5385           7 :           ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
    5386             : 
    5387          45 :     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
    5388             :   };
    5389             : 
    5390             :   // First gather all vectors used as an immediate source for this BUILD_VECTOR
    5391             :   // node.
    5392         248 :   SmallVector<ShuffleSourceInfo, 2> Sources;
    5393         152 :   for (unsigned i = 0; i < NumElts; ++i) {
    5394         294 :     SDValue V = Op.getOperand(i);
    5395         294 :     if (V.isUndef())
    5396           0 :       continue;
    5397         294 :     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
    5398          58 :              !isa<ConstantSDNode>(V.getOperand(1))) {
    5399             :       DEBUG(dbgs() << "Reshuffle failed: "
    5400             :                       "a shuffle can only come from building a vector from "
    5401             :                       "various elements of other vectors, provided their "
    5402             :                       "indices are constant\n");
    5403         119 :       return SDValue();
    5404             :     }
    5405             : 
    5406             :     // Add this element source to the list if it's not already there.
    5407          56 :     SDValue SourceVec = V.getOperand(0);
    5408          28 :     auto Source = find(Sources, SourceVec);
    5409          28 :     if (Source == Sources.end())
    5410           7 :       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
    5411             : 
    5412             :     // Update the minimum and maximum lane number seen.
    5413         112 :     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
    5414          56 :     Source->MinElt = std::min(Source->MinElt, EltNo);
    5415          56 :     Source->MaxElt = std::max(Source->MaxElt, EltNo);
    5416             :   }
    5417             : 
    5418           5 :   if (Sources.size() > 2) {
    5419             :     DEBUG(dbgs() << "Reshuffle failed: currently only do something sane when at "
    5420             :                     "most two source vectors are involved\n");
    5421           0 :     return SDValue();
    5422             :   }
    5423             : 
    5424             :   // Find out the smallest element size among result and two sources, and use
    5425             :   // it as element size to build the shuffle_vector.
    5426           5 :   EVT SmallestEltTy = VT.getVectorElementType();
    5427          22 :   for (auto &Source : Sources) {
    5428          14 :     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
    5429           7 :     if (SrcEltTy.bitsLT(SmallestEltTy)) {
    5430           1 :       SmallestEltTy = SrcEltTy;
    5431             :     }
    5432             :   }
    5433             :   unsigned ResMultiplier =
    5434           5 :       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
    5435           5 :   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
    5436           5 :   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
    5437             : 
    5438             :   // If the source vector is too wide or too narrow, we may nevertheless be able
    5439             :   // to construct a compatible shuffle either by concatenating it with UNDEF or
    5440             :   // extracting a suitable range of elements.
    5441          20 :   for (auto &Src : Sources) {
    5442          14 :     EVT SrcVT = Src.ShuffleVec.getValueType();
    5443             : 
    5444           7 :     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
    5445           2 :       continue;
    5446             : 
    5447             :     // This stage of the search produces a source with the same element type as
    5448             :     // the original, but with a total width matching the BUILD_VECTOR output.
    5449           6 :     EVT EltVT = SrcVT.getVectorElementType();
    5450           6 :     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
    5451           6 :     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
    5452             : 
    5453           6 :     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
    5454             :       assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
    5455             :       // We can pad out the smaller vector for free, so if it's part of a
    5456             :       // shuffle...
    5457           0 :       Src.ShuffleVec =
    5458           0 :           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
    5459           0 :                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
    5460           0 :       continue;
    5461             :     }
    5462             : 
    5463             :     assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
    5464             : 
    5465           6 :     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
    5466             :       DEBUG(dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
    5467           2 :       return SDValue();
    5468             :     }
    5469             : 
    5470           4 :     if (Src.MinElt >= NumSrcElts) {
    5471             :       // The extraction can just take the second half
    5472           1 :       Src.ShuffleVec =
    5473           2 :           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
    5474           3 :                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
    5475           1 :       Src.WindowBase = -NumSrcElts;
    5476           3 :     } else if (Src.MaxElt < NumSrcElts) {
    5477             :       // The extraction can just take the first half
    5478           2 :       Src.ShuffleVec =
    5479           4 :           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
    5480           6 :                       DAG.getConstant(0, dl, MVT::i64));
    5481             :     } else {
    5482             :       // An actual VEXT is needed
    5483             :       SDValue VEXTSrc1 =
    5484             :           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
    5485           2 :                       DAG.getConstant(0, dl, MVT::i64));
    5486             :       SDValue VEXTSrc2 =
    5487             :           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
    5488           2 :                       DAG.getConstant(NumSrcElts, dl, MVT::i64));
    5489           1 :       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
    5490             : 
    5491           1 :       Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
    5492             :                                    VEXTSrc2,
    5493           2 :                                    DAG.getConstant(Imm, dl, MVT::i32));
    5494           1 :       Src.WindowBase = -Src.MinElt;
    5495             :     }
    5496             :   }
    5497             : 
    5498             :   // Another possible incompatibility occurs from the vector element types. We
    5499             :   // can fix this by bitcasting the source vectors to the same type we intend
    5500             :   // for the shuffle.
    5501          14 :   for (auto &Src : Sources) {
    5502          10 :     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
    5503           5 :     if (SrcEltTy == SmallestEltTy)
    5504           4 :       continue;
    5505             :     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
    5506           1 :     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
    5507           1 :     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
    5508           1 :     Src.WindowBase *= Src.WindowScale;
    5509             :   }
    5510             : 
    5511             :   // Final sanity check before we try to actually produce a shuffle.
    5512             :   DEBUG(
    5513             :     for (auto Src : Sources)
    5514             :       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
    5515             :   );
    5516             : 
    5517             :   // The stars all align, our next step is to produce the mask for the shuffle.
    5518           6 :   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
    5519           3 :   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
    5520          15 :   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
    5521          24 :     SDValue Entry = Op.getOperand(i);
    5522          24 :     if (Entry.isUndef())
    5523           0 :       continue;
    5524             : 
    5525          36 :     auto Src = find(Sources, Entry.getOperand(0));
    5526          48 :     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
    5527             : 
    5528             :     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
    5529             :     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
    5530             :     // segment.
    5531          36 :     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
    5532             :     int BitsDefined =
    5533          24 :         std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
    5534          12 :     int LanesDefined = BitsDefined / BitsPerShuffleLane;
    5535             : 
    5536             :     // This source is expected to fill ResMultiplier lanes of the final shuffle,
    5537             :     // starting at the appropriate offset.
    5538          24 :     int *LaneMask = &Mask[i * ResMultiplier];
    5539             : 
    5540          12 :     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
    5541          24 :     ExtractBase += NumElts * (Src - Sources.begin());
    5542          24 :     for (int j = 0; j < LanesDefined; ++j)
    5543          12 :       LaneMask[j] = ExtractBase + j;
    5544             :   }
    5545             : 
    5546             :   // Final check before we try to produce nonsense...
    5547           6 :   if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
    5548             :     DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
    5549           0 :     return SDValue();
    5550             :   }
    5551             : 
    5552           3 :   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
    5553          16 :   for (unsigned i = 0; i < Sources.size(); ++i)
    5554          10 :     ShuffleOps[i] = Sources[i].ShuffleVec;
    5555             : 
    5556             :   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
    5557           3 :                                          ShuffleOps[1], Mask);
    5558           3 :   SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
    5559             : 
    5560             :   DEBUG(
    5561             :     dbgs() << "Reshuffle, creating node: ";
    5562             :     Shuffle.dump();
    5563             :     dbgs() << "Reshuffle, creating node: ";
    5564             :     V.dump();
    5565             :   );
    5566             : 
    5567           3 :   return V;
    5568             : }
    5569             : 
    5570             : // check if an EXT instruction can handle the shuffle mask when the
    5571             : // vector sources of the shuffle are the same.
    5572         172 : static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
    5573         172 :   unsigned NumElts = VT.getVectorNumElements();
    5574             : 
    5575             :   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
    5576         172 :   if (M[0] < 0)
    5577             :     return false;
    5578             : 
    5579         172 :   Imm = M[0];
    5580             : 
    5581             :   // If this is a VEXT shuffle, the immediate value is the index of the first
    5582             :   // element.  The other shuffle indices must be the successive elements after
    5583             :   // the first one.
    5584         172 :   unsigned ExpectedElt = Imm;
    5585         327 :   for (unsigned i = 1; i < NumElts; ++i) {
    5586             :     // Increment the expected index.  If it wraps around, just follow it
    5587             :     // back to index zero and keep going.
    5588         307 :     ++ExpectedElt;
    5589         307 :     if (ExpectedElt == NumElts)
    5590          26 :       ExpectedElt = 0;
    5591             : 
    5592         614 :     if (M[i] < 0)
    5593             :       continue; // ignore UNDEF indices
    5594         276 :     if (ExpectedElt != static_cast<unsigned>(M[i]))
    5595             :       return false;
    5596             :   }
    5597             : 
    5598             :   return true;
    5599             : }
    5600             : 
    5601             : // check if an EXT instruction can handle the shuffle mask when the
    5602             : // vector sources of the shuffle are different.
    5603         582 : static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
    5604             :                       unsigned &Imm) {
    5605             :   // Look for the first non-undef element.
    5606        1164 :   const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
    5607             : 
    5608             :   // Benefit form APInt to handle overflow when calculating expected element.
    5609         582 :   unsigned NumElts = VT.getVectorNumElements();
    5610        2328 :   unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
    5611        1746 :   APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
    5612             :   // The following shuffle indices must be the successive elements after the
    5613             :   // first real element.
    5614         582 :   const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
    5615        3615 :       [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
    5616         582 :   if (FirstWrongElt != M.end())
    5617             :     return false;
    5618             : 
    5619             :   // The index of an EXT is the first element if it is not UNDEF.
    5620             :   // Watch out for the beginning UNDEFs. The EXT index should be the expected
    5621             :   // value of the first element.  E.g.
    5622             :   // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
    5623             :   // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
    5624             :   // ExpectedElt is the last mask index plus 1.
    5625          64 :   Imm = ExpectedElt.getZExtValue();
    5626             : 
    5627             :   // There are two difference cases requiring to reverse input vectors.
    5628             :   // For example, for vector <4 x i32> we have the following cases,
    5629             :   // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
    5630             :   // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
    5631             :   // For both cases, we finally use mask <5, 6, 7, 0>, which requires
    5632             :   // to reverse two input vectors.
    5633          64 :   if (Imm < NumElts)
    5634          23 :     ReverseEXT = true;
    5635             :   else
    5636          41 :     Imm -= NumElts;
    5637             : 
    5638             :   return true;
    5639             : }
    5640             : 
    5641             : /// isREVMask - Check if a vector shuffle corresponds to a REV
    5642             : /// instruction with the specified blocksize.  (The order of the elements
    5643             : /// within each block of the vector is reversed.)
    5644        1822 : static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
    5645             :   assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
    5646             :          "Only possible block sizes for REV are: 16, 32, 64");
    5647             : 
    5648        1822 :   unsigned EltSz = VT.getScalarSizeInBits();
    5649        1822 :   if (EltSz == 64)
    5650             :     return false;
    5651             : 
    5652        1714 :   unsigned NumElts = VT.getVectorNumElements();
    5653        1714 :   unsigned BlockElts = M[0] + 1;
    5654             :   // If the first shuffle index is UNDEF, be optimistic.
    5655        1714 :   if (M[0] < 0)
    5656          55 :     BlockElts = BlockSize / EltSz;
    5657             : 
    5658        1714 :   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
    5659             :     return false;
    5660             : 
    5661        1477 :   for (unsigned i = 0; i < NumElts; ++i) {
    5662        1654 :     if (M[i] < 0)
    5663             :       continue; // ignore UNDEF indices
    5664         659 :     if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
    5665             :       return false;
    5666             :   }
    5667             : 
    5668             :   return true;
    5669             : }
    5670             : 
    5671         479 : static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
    5672         479 :   unsigned NumElts = VT.getVectorNumElements();
    5673         479 :   WhichResult = (M[0] == 0 ? 0 : 1);
    5674         479 :   unsigned Idx = WhichResult * NumElts / 2;
    5675        1019 :   for (unsigned i = 0; i != NumElts; i += 2) {
    5676        2374 :     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
    5677        1891 :         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
    5678             :       return false;
    5679         540 :     Idx += 1;
    5680             :   }
    5681             : 
    5682             :   return true;
    5683             : }
    5684             : 
    5685         310 : static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
    5686         310 :   unsigned NumElts = VT.getVectorNumElements();
    5687         310 :   WhichResult = (M[0] == 0 ? 0 : 1);
    5688        1436 :   for (unsigned i = 0; i != NumElts; ++i) {
    5689        2656 :     if (M[i] < 0)
    5690             :       continue; // ignore UNDEF indices
    5691        1196 :     if ((unsigned)M[i] != 2 * i + WhichResult)
    5692             :       return false;
    5693             :   }
    5694             : 
    5695             :   return true;
    5696             : }
    5697             : 
    5698         221 : static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
    5699         221 :   unsigned NumElts = VT.getVectorNumElements();
    5700         221 :   WhichResult = (M[0] == 0 ? 0 : 1);
    5701         543 :   for (unsigned i = 0; i < NumElts; i += 2) {
    5702        1321 :     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
    5703        1269 :         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
    5704             :       return false;
    5705             :   }
    5706             :   return true;
    5707             : }
    5708             : 
    5709             : /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
    5710             : /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
    5711             : /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
    5712         125 : static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
    5713         125 :   unsigned NumElts = VT.getVectorNumElements();
    5714         125 :   WhichResult = (M[0] == 0 ? 0 : 1);
    5715         125 :   unsigned Idx = WhichResult * NumElts / 2;
    5716         265 :   for (unsigned i = 0; i != NumElts; i += 2) {
    5717         644 :     if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
    5718         522 :         (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
    5719             :       return false;
    5720         140 :     Idx += 1;
    5721             :   }
    5722             : 
    5723             :   return true;
    5724             : }
    5725             : 
    5726             : /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
    5727             : /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
    5728             : /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
    5729          95 : static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
    5730          95 :   unsigned Half = VT.getVectorNumElements() / 2;
    5731          95 :   WhichResult = (M[0] == 0 ? 0 : 1);
    5732         155 :   for (unsigned j = 0; j != 2; ++j) {
    5733             :     unsigned Idx = WhichResult;
    5734         723 :     for (unsigned i = 0; i != Half; ++i) {
    5735         728 :       int MIdx = M[i + j * Half];
    5736         364 :       if (MIdx >= 0 && (unsigned)MIdx != Idx)
    5737             :         return false;
    5738         299 :       Idx += 2;
    5739             :     }
    5740             :   }
    5741             : 
    5742             :   return true;
    5743             : }
    5744             : 
    5745             : /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
    5746             : /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
    5747             : /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
    5748          65 : static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
    5749          65 :   unsigned NumElts = VT.getVectorNumElements();
    5750          65 :   WhichResult = (M[0] == 0 ? 0 : 1);
    5751         193 :   for (unsigned i = 0; i < NumElts; i += 2) {
    5752         475 :     if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
    5753         447 :         (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
    5754             :       return false;
    5755             :   }
    5756             :   return true;
    5757             : }
    5758             : 
    5759          25 : static bool isINSMask(ArrayRef<int> M, int NumInputElements,
    5760             :                       bool &DstIsLeft, int &Anomaly) {
    5761          25 :   if (M.size() != static_cast<size_t>(NumInputElements))
    5762             :     return false;
    5763             : 
    5764             :   int NumLHSMatch = 0, NumRHSMatch = 0;
    5765             :   int LastLHSMismatch = -1, LastRHSMismatch = -1;
    5766             : 
    5767         425 :   for (int i = 0; i < NumInputElements; ++i) {
    5768         401 :     if (M[i] == -1) {
    5769           1 :       ++NumLHSMatch;
    5770           1 :       ++NumRHSMatch;
    5771           1 :       continue;
    5772             :     }
    5773             : 
    5774         199 :     if (M[i] == i)
    5775          90 :       ++NumLHSMatch;
    5776             :     else
    5777             :       LastLHSMismatch = i;
    5778             : 
    5779         199 :     if (M[i] == i + NumInputElements)
    5780          27 :       ++NumRHSMatch;
    5781             :     else
    5782             :       LastRHSMismatch = i;
    5783             :   }
    5784             : 
    5785          25 :   if (NumLHSMatch == NumInputElements - 1) {
    5786           4 :     DstIsLeft = true;
    5787           4 :     Anomaly = LastLHSMismatch;
    5788           4 :     return true;
    5789          21 :   } else if (NumRHSMatch == NumInputElements - 1) {
    5790           2 :     DstIsLeft = false;
    5791           2 :     Anomaly = LastRHSMismatch;
    5792           2 :     return true;
    5793             :   }
    5794             : 
    5795             :   return false;
    5796             : }
    5797             : 
    5798          35 : static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
    5799          35 :   if (VT.getSizeInBits() != 128)
    5800             :     return false;
    5801             : 
    5802          24 :   unsigned NumElts = VT.getVectorNumElements();
    5803             : 
    5804          97 :   for (int I = 0, E = NumElts / 2; I != E; I++) {
    5805         170 :     if (Mask[I] != I)
    5806             :       return false;
    5807             :   }
    5808             : 
    5809          12 :   int Offset = NumElts / 2;
    5810          70 :   for (int I = NumElts / 2, E = NumElts; I != E; I++) {
    5811         118 :     if (Mask[I] != I + SplitLHS * Offset)
    5812             :       return false;
    5813             :   }
    5814             : 
    5815             :   return true;
    5816             : }
    5817             : 
    5818          30 : static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
    5819          60 :   SDLoc DL(Op);
    5820          60 :   EVT VT = Op.getValueType();
    5821          60 :   SDValue V0 = Op.getOperand(0);
    5822          60 :   SDValue V1 = Op.getOperand(1);
    5823          60 :   ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
    5824             : 
    5825          90 :   if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
    5826          90 :       VT.getVectorElementType() != V1.getValueType().getVectorElementType())
    5827           0 :     return SDValue();
    5828             : 
    5829          30 :   bool SplitV0 = V0.getValueSizeInBits() == 128;
    5830             : 
    5831          30 :   if (!isConcatMask(Mask, VT, SplitV0))
    5832          20 :     return SDValue();
    5833             : 
    5834          10 :   EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
    5835          20 :                                 VT.getVectorNumElements() / 2);
    5836          10 :   if (SplitV0) {
    5837          10 :     V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
    5838          30 :                      DAG.getConstant(0, DL, MVT::i64));
    5839             :   }
    5840          10 :   if (V1.getValueSizeInBits() == 128) {
    5841          10 :     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
    5842          30 :                      DAG.getConstant(0, DL, MVT::i64));
    5843             :   }
    5844          10 :   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
    5845             : }
    5846             : 
    5847             : /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
    5848             : /// the specified operations to build the shuffle.
    5849          57 : static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
    5850             :                                       SDValue RHS, SelectionDAG &DAG,
    5851             :                                       const SDLoc &dl) {
    5852          57 :   unsigned OpNum = (PFEntry >> 26) & 0x0F;
    5853          57 :   unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
    5854          57 :   unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
    5855             : 
    5856             :   enum {
    5857             :     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
    5858             :     OP_VREV,
    5859             :     OP_VDUP0,
    5860             :     OP_VDUP1,
    5861             :     OP_VDUP2,
    5862             :     OP_VDUP3,
    5863             :     OP_VEXT1,
    5864             :     OP_VEXT2,
    5865             :     OP_VEXT3,
    5866             :     OP_VUZPL, // VUZP, left result
    5867             :     OP_VUZPR, // VUZP, right result
    5868             :     OP_VZIPL, // VZIP, left result
    5869             :     OP_VZIPR, // VZIP, right result
    5870             :     OP_VTRNL, // VTRN, left result
    5871             :     OP_VTRNR  // VTRN, right result
    5872             :   };
    5873             : 
    5874          57 :   if (OpNum == OP_COPY) {
    5875          33 :     if (LHSID == (1 * 9 + 2) * 9 + 3)
    5876          22 :       return LHS;
    5877             :     assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
    5878          11 :     return RHS;
    5879             :   }
    5880             : 
    5881          24 :   SDValue OpLHS, OpRHS;
    5882          24 :   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
    5883          24 :   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
    5884          48 :   EVT VT = OpLHS.getValueType();
    5885             : 
    5886          24 :   switch (OpNum) {
    5887           0 :   default:
    5888           0 :     llvm_unreachable("Unknown shuffle opcode!");
    5889           1 :   case OP_VREV:
    5890             :     // VREV divides the vector in half and swaps within the half.
    5891           2 :     if (VT.getVectorElementType() == MVT::i32 ||
    5892           2 :         VT.getVectorElementType() == MVT::f32)
    5893           1 :       return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
    5894             :     // vrev <4 x i16> -> REV32
    5895           0 :     if (VT.getVectorElementType() == MVT::i16 ||
    5896           0 :         VT.getVectorElementType() == MVT::f16)
    5897           0 :       return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
    5898             :     // vrev <4 x i8> -> REV16
    5899             :     assert(VT.getVectorElementType() == MVT::i8);
    5900           0 :     return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
    5901           8 :   case OP_VDUP0:
    5902             :   case OP_VDUP1:
    5903             :   case OP_VDUP2:
    5904             :   case OP_VDUP3: {
    5905           8 :     EVT EltTy = VT.getVectorElementType();
    5906             :     unsigned Opcode;
    5907          16 :     if (EltTy == MVT::i8)
    5908             :       Opcode = AArch64ISD::DUPLANE8;
    5909          13 :     else if (EltTy == MVT::i16 || EltTy == MVT::f16)
    5910             :       Opcode = AArch64ISD::DUPLANE16;
    5911           7 :     else if (EltTy == MVT::i32 || EltTy == MVT::f32)
    5912             :       Opcode = AArch64ISD::DUPLANE32;
    5913           0 :     else if (EltTy == MVT::i64 || EltTy == MVT::f64)
    5914             :       Opcode = AArch64ISD::DUPLANE64;
    5915             :     else
    5916           0 :       llvm_unreachable("Invalid vector element type?");
    5917             : 
    5918           8 :     if (VT.getSizeInBits() == 64)
    5919           4 :       OpLHS = WidenVector(OpLHS, DAG);
    5920           8 :     SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
    5921           8 :     return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
    5922             :   }
    5923          11 :   case OP_VEXT1:
    5924             :   case OP_VEXT2:
    5925             :   case OP_VEXT3: {
    5926          11 :     unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
    5927             :     return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
    5928          11 :                        DAG.getConstant(Imm, dl, MVT::i32));
    5929             :   }
    5930           1 :   case OP_VUZPL:
    5931             :     return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
    5932           1 :                        OpRHS);
    5933           0 :   case OP_VUZPR:
    5934             :     return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
    5935           0 :                        OpRHS);
    5936           3 :   case OP_VZIPL:
    5937             :     return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
    5938           3 :                        OpRHS);
    5939           0 :   case OP_VZIPR:
    5940             :     return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
    5941           0 :                        OpRHS);
    5942           0 :   case OP_VTRNL:
    5943             :     return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
    5944           0 :                        OpRHS);
    5945           0 :   case OP_VTRNR:
    5946             :     return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
    5947           0 :                        OpRHS);
    5948             :   }
    5949             : }
    5950             : 
    5951           5 : static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
    5952             :                            SelectionDAG &DAG) {
    5953             :   // Check to see if we can use the TBL instruction.
    5954          10 :   SDValue V1 = Op.getOperand(0);
    5955          10 :   SDValue V2 = Op.getOperand(1);
    5956          10 :   SDLoc DL(Op);
    5957             : 
    5958          10 :   EVT EltVT = Op.getValueType().getVectorElementType();
    5959           5 :   unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
    5960             : 
    5961          10 :   SmallVector<SDValue, 8> TBLMask;
    5962          66 :   for (int Val : ShuffleMask) {
    5963         120 :     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
    5964          64 :       unsigned Offset = Byte + Val * BytesPerElt;
    5965          64 :       TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
    5966             :     }
    5967             :   }
    5968             : 
    5969           5 :   MVT IndexVT = MVT::v8i8;
    5970           5 :   unsigned IndexLen = 8;
    5971           5 :   if (Op.getValueSizeInBits() == 128) {
    5972           3 :     IndexVT = MVT::v16i8;
    5973           3 :     IndexLen = 16;
    5974             :   }
    5975             : 
    5976          10 :   SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
    5977          10 :   SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
    5978             : 
    5979           5 :   SDValue Shuffle;
    5980           5 :   if (V2.getNode()->isUndef()) {
    5981           1 :     if (IndexLen == 8)
    5982           0 :       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
    5983           1 :     Shuffle = DAG.getNode(
    5984             :         ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
    5985           1 :         DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
    5986             :         DAG.getBuildVector(IndexVT, DL,
    5987           7 :                            makeArrayRef(TBLMask.data(), IndexLen)));
    5988             :   } else {
    5989           4 :     if (IndexLen == 8) {
    5990           4 :       V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
    5991           2 :       Shuffle = DAG.getNode(
    5992             :           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
    5993           2 :           DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
    5994             :           DAG.getBuildVector(IndexVT, DL,
    5995          14 :                              makeArrayRef(TBLMask.data(), IndexLen)));
    5996             :     } else {
    5997             :       // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
    5998             :       // cannot currently represent the register constraints on the input
    5999             :       // table registers.
    6000             :       //  Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
    6001             :       //                   DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
    6002             :       //                   IndexLen));
    6003           2 :       Shuffle = DAG.getNode(
    6004             :           ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
    6005           2 :           DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
    6006             :           V2Cst, DAG.getBuildVector(IndexVT, DL,
    6007          14 :                                     makeArrayRef(TBLMask.data(), IndexLen)));
    6008             :     }
    6009             :   }
    6010          15 :   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
    6011             : }
    6012             : 
    6013             : static unsigned getDUPLANEOp(EVT EltType) {
    6014        1481 :   if (EltType == MVT::i8)
    6015             :     return AArch64ISD::DUPLANE8;
    6016        1158 :   if (EltType == MVT::i16 || EltType == MVT::f16)
    6017             :     return AArch64ISD::DUPLANE16;
    6018         536 :   if (EltType == MVT::i32 || EltType == MVT::f32)
    6019             :     return AArch64ISD::DUPLANE32;
    6020          52 :   if (EltType == MVT::i64 || EltType == MVT::f64)
    6021             :     return AArch64ISD::DUPLANE64;
    6022             : 
    6023           0 :   llvm_unreachable("Invalid vector element type?");
    6024             : }
    6025             : 
    6026        1345 : SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
    6027             :                                                    SelectionDAG &DAG) const {
    6028        2690 :   SDLoc dl(Op);
    6029        2690 :   EVT VT = Op.getValueType();
    6030             : 
    6031        2690 :   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
    6032             : 
    6033             :   // Convert shuffles that are directly supported on NEON to target-specific
    6034             :   // DAG nodes, instead of keeping them as shuffles and matching them again
    6035             :   // during code selection.  This is more efficient and avoids the possibility
    6036             :   // of inconsistencies between legalization and selection.
    6037        1345 :   ArrayRef<int> ShuffleMask = SVN->getMask();
    6038             : 
    6039        2690 :   SDValue V1 = Op.getOperand(0);
    6040        2690 :   SDValue V2 = Op.getOperand(1);
    6041             : 
    6042        1345 :   if (SVN->isSplat()) {
    6043         749 :     int Lane = SVN->getSplatIndex();
    6044             :     // If this is undef splat, generate it via "just" vdup, if possible.
    6045         749 :     if (Lane == -1)
    6046             :       Lane = 0;
    6047             : 
    6048        1079 :     if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
    6049             :       return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
    6050           0 :                          V1.getOperand(0));
    6051             :     // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
    6052             :     // constant. If so, we can just reference the lane's definition directly.
    6053        1498 :     if (V1.getOpcode() == ISD::BUILD_VECTOR &&
    6054           0 :         !isa<ConstantSDNode>(V1.getOperand(Lane)))
    6055           0 :       return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
    6056             : 
    6057             :     // Otherwise, duplicate from the lane of the input vector.
    6058        2247 :     unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
    6059             : 
    6060             :     // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
    6061             :     // to make a vector of the same size as this SHUFFLE. We can ignore the
    6062             :     // extract entirely, and canonicalise the concat using WidenVector.
    6063        1498 :     if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
    6064         704 :       Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
    6065         352 :       V1 = V1.getOperand(0);
    6066        1146 :     } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
    6067          86 :       unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
    6068          86 :       Lane -= Idx * VT.getVectorNumElements() / 2;
    6069         172 :       V1 = WidenVector(V1.getOperand(Idx), DAG);
    6070         487 :     } else if (VT.getSizeInBits() == 64)
    6071         320 :       V1 = WidenVector(V1, DAG);
    6072             : 
    6073        1498 :     return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
    6074             :   }
    6075             : 
    6076         596 :   if (isREVMask(ShuffleMask, VT, 64))
    6077          36 :     return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
    6078         578 :   if (isREVMask(ShuffleMask, VT, 32))
    6079          32 :     return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
    6080         562 :   if (isREVMask(ShuffleMask, VT, 16))
    6081          16 :     return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
    6082             : 
    6083         554 :   bool ReverseEXT = false;
    6084             :   unsigned Imm;
    6085         554 :   if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
    6086          61 :     if (ReverseEXT)
    6087             :       std::swap(V1, V2);
    6088          61 :     Imm *= getExtFactor(V1);
    6089             :     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
    6090         122 :                        DAG.getConstant(Imm, dl, MVT::i32));
    6091         493 :   } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
    6092          20 :     Imm *= getExtFactor(V1);
    6093             :     return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
    6094          40 :                        DAG.getConstant(Imm, dl, MVT::i32));
    6095             :   }
    6096             : 
    6097             :   unsigned WhichResult;
    6098         473 :   if (isZIPMask(ShuffleMask, VT, WhichResult)) {
    6099         169 :     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
    6100         338 :     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
    6101             :   }
    6102         304 :   if (isUZPMask(ShuffleMask, VT, WhichResult)) {
    6103         108 :     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
    6104         216 :     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
    6105             :   }
    6106         196 :   if (isTRNMask(ShuffleMask, VT, WhichResult)) {
    6107          76 :     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
    6108         152 :     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
    6109             :   }
    6110             : 
    6111         120 :   if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
    6112          30 :     unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
    6113          60 :     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
    6114             :   }
    6115          90 :   if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
    6116          30 :     unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
    6117          60 :     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
    6118             :   }
    6119          60 :   if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
    6120          30 :     unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
    6121          60 :     return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
    6122             :   }
    6123             : 
    6124          30 :   if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
    6125          10 :     return Concat;
    6126             : 
    6127             :   bool DstIsLeft;
    6128             :   int Anomaly;
    6129          40 :   int NumInputElements = V1.getValueType().getVectorNumElements();
    6130          20 :   if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
    6131           6 :     SDValue DstVec = DstIsLeft ? V1 : V2;
    6132           6 :     SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
    6133             : 
    6134           6 :     SDValue SrcVec = V1;
    6135          12 :     int SrcLane = ShuffleMask[Anomaly];
    6136           6 :     if (SrcLane >= NumInputElements) {
    6137           4 :       SrcVec = V2;
    6138           4 :       SrcLane -= VT.getVectorNumElements();
    6139             :     }
    6140           6 :     SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
    6141             : 
    6142           6 :     EVT ScalarVT = VT.getVectorElementType();
    6143             : 
    6144           6 :     if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
    6145           4 :       ScalarVT = MVT::i32;
    6146             : 
    6147             :     return DAG.getNode(
    6148             :         ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
    6149             :         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
    6150           6 :         DstLaneV);
    6151             :   }
    6152             : 
    6153             :   // If the shuffle is not directly supported and it has 4 elements, use
    6154             :   // the PerfectShuffle-generated table to synthesize it from other shuffles.
    6155          14 :   unsigned NumElts = VT.getVectorNumElements();
    6156          14 :   if (NumElts == 4) {
    6157             :     unsigned PFIndexes[4];
    6158          81 :     for (unsigned i = 0; i != 4; ++i) {
    6159          72 :       if (ShuffleMask[i] < 0)
    6160           1 :         PFIndexes[i] = 8;
    6161             :       else
    6162          35 :         PFIndexes[i] = ShuffleMask[i];
    6163             :     }
    6164             : 
    6165             :     // Compute the index in the perfect shuffle table.
    6166          27 :     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
    6167          18 :                             PFIndexes[2] * 9 + PFIndexes[3];
    6168           9 :     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
    6169           9 :     unsigned Cost = (PFEntry >> 30);
    6170             : 
    6171             :     if (Cost <= 4)
    6172           9 :       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
    6173             :   }
    6174             : 
    6175           5 :   return GenerateTBL(Op, ShuffleMask, DAG);
    6176             : }
    6177             : 
    6178        1852 : static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
    6179             :                                APInt &UndefBits) {
    6180        3704 :   EVT VT = BVN->getValueType(0);
    6181        7408 :   APInt SplatBits, SplatUndef;
    6182             :   unsigned SplatBitSize;
    6183             :   bool HasAnyUndefs;
    6184        1852 :   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
    6185        1275 :     unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
    6186             : 
    6187       12684 :     for (unsigned i = 0; i < NumSplats; ++i) {
    6188       11409 :       CnstBits <<= SplatBitSize;
    6189       11409 :       UndefBits <<= SplatBitSize;
    6190       34227 :       CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
    6191       68454 :       UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
    6192             :     }
    6193             : 
    6194             :     return true;
    6195             :   }
    6196             : 
    6197             :   return false;
    6198             : }
    6199             : 
    6200         595 : SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
    6201             :                                               SelectionDAG &DAG) const {
    6202             :   BuildVectorSDNode *BVN =
    6203        1785 :       dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
    6204        1190 :   SDValue LHS = Op.getOperand(0);
    6205        1190 :   SDLoc dl(Op);
    6206        1190 :   EVT VT = Op.getValueType();
    6207             : 
    6208         595 :   if (!BVN)
    6209         462 :     return Op;
    6210             : 
    6211         266 :   APInt CnstBits(VT.getSizeInBits(), 0);
    6212         399 :   APInt UndefBits(VT.getSizeInBits(), 0);
    6213         133 :   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
    6214             :     // We only have BIC vector immediate instruction, which is and-not.
    6215         655 :     CnstBits = ~CnstBits;
    6216             : 
    6217             :     // We make use of a little bit of goto ickiness in order to avoid having to
    6218             :     // duplicate the immediate matching logic for the undef toggled case.
    6219         131 :     bool SecondTry = false;
    6220         198 :   AttemptModImm:
    6221             : 
    6222         792 :     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
    6223         564 :       CnstBits = CnstBits.zextOrTrunc(64);
    6224         188 :       uint64_t CnstVal = CnstBits.getZExtValue();
    6225             : 
    6226         188 :       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
    6227           9 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
    6228          18 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6229             :         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
    6230           9 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6231          27 :                                   DAG.getConstant(0, dl, MVT::i32));
    6232           9 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6233             :       }
    6234             : 
    6235         179 :       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
    6236           9 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
    6237          18 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6238             :         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
    6239           9 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6240          27 :                                   DAG.getConstant(8, dl, MVT::i32));
    6241           9 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6242             :       }
    6243             : 
    6244         170 :       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
    6245           9 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
    6246          18 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6247             :         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
    6248           9 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6249          27 :                                   DAG.getConstant(16, dl, MVT::i32));
    6250           9 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6251             :       }
    6252             : 
    6253         161 :       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
    6254          11 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
    6255          22 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6256             :         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
    6257          11 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6258          33 :                                   DAG.getConstant(24, dl, MVT::i32));
    6259          11 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6260             :       }
    6261             : 
    6262         150 :       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
    6263          11 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
    6264          22 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
    6265             :         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
    6266          11 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6267          33 :                                   DAG.getConstant(0, dl, MVT::i32));
    6268          11 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6269             :       }
    6270             : 
    6271          15 :       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
    6272          15 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
    6273          30 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
    6274             :         SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
    6275          15 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6276          45 :                                   DAG.getConstant(8, dl, MVT::i32));
    6277          15 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6278             :       }
    6279             :     }
    6280             : 
    6281         134 :     if (SecondTry)
    6282             :       goto FailedModImm;
    6283          67 :     SecondTry = true;
    6284         335 :     CnstBits = ~UndefBits;
    6285          67 :     goto AttemptModImm;
    6286             :   }
    6287             : 
    6288             : // We can always fall back to a non-immediate AND.
    6289          69 : FailedModImm:
    6290          69 :   return Op;
    6291             : }
    6292             : 
    6293             : // Specialized code to quickly find if PotentialBVec is a BuildVector that
    6294             : // consists of only the same constant int value, returned in reference arg
    6295             : // ConstVal
    6296           8 : static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
    6297             :                                      uint64_t &ConstVal) {
    6298           6 :   BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
    6299             :   if (!Bvec)
    6300             :     return false;
    6301          18 :   ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
    6302             :   if (!FirstElt)
    6303             :     return false;
    6304          12 :   EVT VT = Bvec->getValueType(0);
    6305           6 :   unsigned NumElts = VT.getVectorNumElements();
    6306          96 :   for (unsigned i = 1; i < NumElts; ++i)
    6307         270 :     if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
    6308             :       return false;
    6309           6 :   ConstVal = FirstElt->getZExtValue();
    6310           6 :   return true;
    6311             : }
    6312             : 
    6313             : static unsigned getIntrinsicID(const SDNode *N) {
    6314        5337 :   unsigned Opcode = N->getOpcode();
    6315        5337 :   switch (Opcode) {
    6316             :   default:
    6317             :     return Intrinsic::not_intrinsic;
    6318        5337 :   case ISD::INTRINSIC_WO_CHAIN: {
    6319       21348 :     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
    6320        5337 :     if (IID < Intrinsic::num_intrinsics)
    6321             :       return IID;
    6322             :     return Intrinsic::not_intrinsic;
    6323             :   }
    6324             :   }
    6325             : }
    6326             : 
    6327             : // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
    6328             : // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
    6329             : // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
    6330             : // Also, logical shift right -> sri, with the same structure.
    6331           8 : static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
    6332          16 :   EVT VT = N->getValueType(0);
    6333             : 
    6334           8 :   if (!VT.isVector())
    6335           0 :     return SDValue();
    6336             : 
    6337           8 :   SDLoc DL(N);
    6338             : 
    6339             :   // Is the first op an AND?
    6340          16 :   const SDValue And = N->getOperand(0);
    6341          16 :   if (And.getOpcode() != ISD::AND)
    6342           0 :     return SDValue();
    6343             : 
    6344             :   // Is the second op an shl or lshr?
    6345          16 :   SDValue Shift = N->getOperand(1);
    6346             :   // This will have been turned into: AArch64ISD::VSHL vector, #shift
    6347             :   // or AArch64ISD::VLSHR vector, #shift
    6348          16 :   unsigned ShiftOpc = Shift.getOpcode();
    6349           8 :   if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
    6350           0 :     return SDValue();
    6351           8 :   bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
    6352             : 
    6353             :   // Is the shift amount constant?
    6354          24 :   ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
    6355             :   if (!C2node)
    6356           0 :     return SDValue();
    6357             : 
    6358             :   // Is the and mask vector all constant?
    6359             :   uint64_t C1;
    6360          16 :   if (!isAllConstantBuildVector(And.getOperand(1), C1))
    6361           2 :     return SDValue();
    6362             : 
    6363             :   // Is C1 == ~C2, taking into account how much one can shift elements of a
    6364             :   // particular size?
    6365           6 :   uint64_t C2 = C2node->getZExtValue();
    6366           6 :   unsigned ElemSizeInBits = VT.getScalarSizeInBits();
    6367           6 :   if (C2 > ElemSizeInBits)
    6368           0 :     return SDValue();
    6369           6 :   unsigned ElemMask = (1 << ElemSizeInBits) - 1;
    6370           6 :   if ((C1 & ElemMask) != (~C2 & ElemMask))
    6371           4 :     return SDValue();
    6372             : 
    6373           4 :   SDValue X = And.getOperand(0);
    6374           4 :   SDValue Y = Shift.getOperand(0);
    6375             : 
    6376           2 :   unsigned Intrin =
    6377           2 :       IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
    6378             :   SDValue ResultSLI =
    6379             :       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
    6380           2 :                   DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
    6381           6 :                   Shift.getOperand(1));
    6382             : 
    6383             :   DEBUG(dbgs() << "aarch64-lower: transformed: \n");
    6384             :   DEBUG(N->dump(&DAG));
    6385             :   DEBUG(dbgs() << "into: \n");
    6386             :   DEBUG(ResultSLI->dump(&DAG));
    6387             : 
    6388           2 :   ++NumShiftInserts;
    6389           2 :   return ResultSLI;
    6390             : }
    6391             : 
    6392         416 : SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
    6393             :                                              SelectionDAG &DAG) const {
    6394             :   // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
    6395         416 :   if (EnableAArch64SlrGeneration) {
    6396           8 :     if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
    6397           2 :       return Res;
    6398             :   }
    6399             : 
    6400             :   BuildVectorSDNode *BVN =
    6401        1242 :       dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
    6402         828 :   SDValue LHS = Op.getOperand(1);
    6403         414 :   SDLoc dl(Op);
    6404         828 :   EVT VT = Op.getValueType();
    6405             : 
    6406             :   // OR commutes, so try swapping the operands.
    6407         414 :   if (!BVN) {
    6408         828 :     LHS = Op.getOperand(0);
    6409         828 :     BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
    6410             :   }
    6411          62 :   if (!BVN)
    6412         352 :     return Op;
    6413             : 
    6414         124 :   APInt CnstBits(VT.getSizeInBits(), 0);
    6415         186 :   APInt UndefBits(VT.getSizeInBits(), 0);
    6416          62 :   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
    6417             :     // We make use of a little bit of goto ickiness in order to avoid having to
    6418             :     // duplicate the immediate matching logic for the undef toggled case.
    6419             :     bool SecondTry = false;
    6420          62 :   AttemptModImm:
    6421             : 
    6422         248 :     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
    6423         186 :       CnstBits = CnstBits.zextOrTrunc(64);
    6424          62 :       uint64_t CnstVal = CnstBits.getZExtValue();
    6425             : 
    6426          62 :       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
    6427          11 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
    6428          22 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6429             :         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
    6430          11 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6431          33 :                                   DAG.getConstant(0, dl, MVT::i32));
    6432          11 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6433             :       }
    6434             : 
    6435          51 :       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
    6436           9 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
    6437          18 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6438             :         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
    6439           9 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6440          27 :                                   DAG.getConstant(8, dl, MVT::i32));
    6441           9 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6442             :       }
    6443             : 
    6444          42 :       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
    6445           9 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
    6446          18 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6447             :         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
    6448           9 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6449          27 :                                   DAG.getConstant(16, dl, MVT::i32));
    6450           9 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6451             :       }
    6452             : 
    6453          33 :       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
    6454          11 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
    6455          22 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6456             :         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
    6457          11 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6458          33 :                                   DAG.getConstant(24, dl, MVT::i32));
    6459          11 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6460             :       }
    6461             : 
    6462          22 :       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
    6463          11 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
    6464          22 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
    6465             :         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
    6466          11 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6467          33 :                                   DAG.getConstant(0, dl, MVT::i32));
    6468          11 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6469             :       }
    6470             : 
    6471          11 :       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
    6472          11 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
    6473          22 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
    6474             :         SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
    6475          11 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6476          33 :                                   DAG.getConstant(8, dl, MVT::i32));
    6477          11 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6478             :       }
    6479             :     }
    6480             : 
    6481           0 :     if (SecondTry)
    6482             :       goto FailedModImm;
    6483           0 :     SecondTry = true;
    6484           0 :     CnstBits = UndefBits;
    6485           0 :     goto AttemptModImm;
    6486             :   }
    6487             : 
    6488             : // We can always fall back to a non-immediate OR.
    6489           0 : FailedModImm:
    6490           0 :   return Op;
    6491             : }
    6492             : 
    6493             : // Normalize the operands of BUILD_VECTOR. The value of constant operands will
    6494             : // be truncated to fit element width.
    6495        1422 : static SDValue NormalizeBuildVector(SDValue Op,
    6496             :                                     SelectionDAG &DAG) {
    6497             :   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
    6498        2844 :   SDLoc dl(Op);
    6499        2844 :   EVT VT = Op.getValueType();
    6500        1422 :   EVT EltTy= VT.getVectorElementType();
    6501             : 
    6502        1422 :   if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
    6503         832 :     return Op;
    6504             : 
    6505         590 :   SmallVector<SDValue, 16> Ops;
    6506        5952 :   for (SDValue Lane : Op->ops()) {
    6507        3359 :     if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
    6508             :       APInt LowBits(EltTy.getSizeInBits(),
    6509       10077 :                     CstLane->getZExtValue());
    6510        6718 :       Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
    6511             :     }
    6512        4772 :     Ops.push_back(Lane);
    6513             :   }
    6514         590 :   return DAG.getBuildVector(VT, dl, Ops);
    6515             : }
    6516             : 
    6517        1422 : SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
    6518             :                                                  SelectionDAG &DAG) const {
    6519        2844 :   SDLoc dl(Op);
    6520        2844 :   EVT VT = Op.getValueType();
    6521        1422 :   Op = NormalizeBuildVector(Op, DAG);
    6522        2844 :   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
    6523             : 
    6524        4266 :   APInt CnstBits(VT.getSizeInBits(), 0);
    6525        4266 :   APInt UndefBits(VT.getSizeInBits(), 0);
    6526        1422 :   if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
    6527             :     // We make use of a little bit of goto ickiness in order to avoid having to
    6528             :     // duplicate the immediate matching logic for the undef toggled case.
    6529             :     bool SecondTry = false;
    6530         917 :   AttemptModImm:
    6531             : 
    6532        3668 :     if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
    6533        2529 :       CnstBits = CnstBits.zextOrTrunc(64);
    6534         843 :       uint64_t CnstVal = CnstBits.getZExtValue();
    6535             : 
    6536             :       // Certain magic vector constants (used to express things like NOT
    6537             :       // and NEG) are passed through unmodified.  This allows codegen patterns
    6538             :       // for these operations to match.  Special-purpose patterns will lower
    6539             :       // these immediates to MOVIs if it proves necessary.
    6540         843 :       if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
    6541         498 :         return Op;
    6542             : 
    6543             :       // The many faces of MOVI...
    6544         345 :       if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
    6545          53 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
    6546          53 :         if (VT.getSizeInBits() == 128) {
    6547             :           SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
    6548          78 :                                     DAG.getConstant(CnstVal, dl, MVT::i32));
    6549          26 :           return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6550             :         }
    6551             : 
    6552             :         // Support the V64 version via subregister insertion.
    6553             :         SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
    6554          81 :                                   DAG.getConstant(CnstVal, dl, MVT::i32));
    6555          27 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6556             :       }
    6557             : 
    6558         292 :       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
    6559          25 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
    6560          50 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6561             :         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
    6562          25 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6563         100 :                                   DAG.getConstant(0, dl, MVT::i32));
    6564          25 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6565             :       }
    6566             : 
    6567         267 :       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
    6568          10 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
    6569          20 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6570             :         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
    6571          10 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6572          40 :                                   DAG.getConstant(8, dl, MVT::i32));
    6573          10 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6574             :       }
    6575             : 
    6576         257 :       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
    6577          12 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
    6578          24 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6579             :         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
    6580          12 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6581          48 :                                   DAG.getConstant(16, dl, MVT::i32));
    6582          12 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6583             :       }
    6584             : 
    6585         245 :       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
    6586          25 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
    6587          50 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6588             :         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
    6589          25 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6590         100 :                                   DAG.getConstant(24, dl, MVT::i32));
    6591          25 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6592             :       }
    6593             : 
    6594         220 :       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
    6595          25 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
    6596          50 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
    6597             :         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
    6598          25 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6599         100 :                                   DAG.getConstant(0, dl, MVT::i32));
    6600          25 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6601             :       }
    6602             : 
    6603         195 :       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
    6604          16 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
    6605          32 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
    6606             :         SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
    6607          16 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6608          64 :                                   DAG.getConstant(8, dl, MVT::i32));
    6609          16 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6610             :       }
    6611             : 
    6612         179 :       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
    6613          11 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
    6614          22 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6615             :         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
    6616          11 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6617          44 :                                   DAG.getConstant(264, dl, MVT::i32));
    6618          11 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6619             :       }
    6620             : 
    6621         168 :       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
    6622          11 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
    6623          22 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6624             :         SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
    6625          11 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6626          44 :                                   DAG.getConstant(272, dl, MVT::i32));
    6627          11 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6628             :       }
    6629             : 
    6630         157 :       if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
    6631          28 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
    6632          56 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
    6633             :         SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
    6634          84 :                                   DAG.getConstant(CnstVal, dl, MVT::i32));
    6635          28 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6636             :       }
    6637             : 
    6638             :       // The few faces of FMOV...
    6639         129 :       if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
    6640          23 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
    6641          46 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
    6642             :         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
    6643          69 :                                   DAG.getConstant(CnstVal, dl, MVT::i32));
    6644          23 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6645             :       }
    6646             : 
    6647          26 :       if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
    6648          13 :           VT.getSizeInBits() == 128) {
    6649          13 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
    6650             :         SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
    6651          39 :                                   DAG.getConstant(CnstVal, dl, MVT::i32));
    6652          13 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6653             :       }
    6654             : 
    6655             :       // The many faces of MVNI...
    6656          93 :       CnstVal = ~CnstVal;
    6657          93 :       if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
    6658           3 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
    6659           6 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6660             :         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
    6661           3 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6662          12 :                                   DAG.getConstant(0, dl, MVT::i32));
    6663           3 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6664             :       }
    6665             : 
    6666          90 :       if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
    6667           3 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
    6668           6 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6669             :         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
    6670           3 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6671          12 :                                   DAG.getConstant(8, dl, MVT::i32));
    6672           3 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6673             :       }
    6674             : 
    6675          87 :       if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
    6676           3 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
    6677           6 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6678             :         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
    6679           3 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6680          12 :                                   DAG.getConstant(16, dl, MVT::i32));
    6681           3 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6682             :       }
    6683             : 
    6684          84 :       if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
    6685           3 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
    6686           6 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6687             :         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
    6688           3 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6689          12 :                                   DAG.getConstant(24, dl, MVT::i32));
    6690           3 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6691             :       }
    6692             : 
    6693          81 :       if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
    6694           4 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
    6695           8 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
    6696             :         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
    6697           4 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6698          16 :                                   DAG.getConstant(0, dl, MVT::i32));
    6699           4 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6700             :       }
    6701             : 
    6702          77 :       if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
    6703           4 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
    6704           8 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
    6705             :         SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
    6706           4 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6707          16 :                                   DAG.getConstant(8, dl, MVT::i32));
    6708           4 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6709             :       }
    6710             : 
    6711          73 :       if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
    6712           4 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
    6713           8 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6714             :         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
    6715           4 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6716          16 :                                   DAG.getConstant(264, dl, MVT::i32));
    6717           4 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6718             :       }
    6719             : 
    6720           3 :       if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
    6721           3 :         CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
    6722           6 :         MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
    6723             :         SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
    6724           3 :                                   DAG.getConstant(CnstVal, dl, MVT::i32),
    6725          12 :                                   DAG.getConstant(272, dl, MVT::i32));
    6726           3 :         return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
    6727             :       }
    6728             :     }
    6729             : 
    6730         140 :     if (SecondTry)
    6731             :       goto FailedModImm;
    6732          70 :     SecondTry = true;
    6733          70 :     CnstBits = UndefBits;
    6734          70 :     goto AttemptModImm;
    6735             :   }
    6736         645 : FailedModImm:
    6737             : 
    6738             :   // Scan through the operands to find some interesting properties we can
    6739             :   // exploit:
    6740             :   //   1) If only one value is used, we can use a DUP, or
    6741             :   //   2) if only the low element is not undef, we can just insert that, or
    6742             :   //   3) if only one constant value is used (w/ some non-constant lanes),
    6743             :   //      we can splat the constant value into the whole vector then fill
    6744             :   //      in the non-constant lanes.
    6745             :   //   4) FIXME: If different constant values are used, but we can intelligently
    6746             :   //             select the values we'll be overwriting for the non-constant
    6747             :   //             lanes such that we can directly materialize the vector
    6748             :   //             some other way (MOVI, e.g.), we can be sneaky.
    6749         645 :   unsigned NumElts = VT.getVectorNumElements();
    6750         645 :   bool isOnlyLowElement = true;
    6751         645 :   bool usesOnlyOneValue = true;
    6752         645 :   bool usesOnlyOneConstantValue = true;
    6753         645 :   bool isConstant = true;
    6754         645 :   unsigned NumConstantLanes = 0;
    6755         645 :   SDValue Value;
    6756         645 :   SDValue ConstantValue;
    6757        3489 :   for (unsigned i = 0; i < NumElts; ++i) {
    6758        5688 :     SDValue V = Op.getOperand(i);
    6759        5688 :     if (V.isUndef())
    6760         645 :       continue;
    6761        2199 :     if (i > 0)
    6762        1557 :       isOnlyLowElement = false;
    6763        2153 :     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
    6764             :       isConstant = false;
    6765             : 
    6766        1715 :     if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
    6767         530 :       ++NumConstantLanes;
    6768         530 :       if (!ConstantValue.getNode())
    6769             :         ConstantValue = V;
    6770         145 :       else if (ConstantValue != V)
    6771             :         usesOnlyOneConstantValue = false;
    6772             :     }
    6773             : 
    6774        2199 :     if (!Value.getNode())
    6775         645 :       Value = V;
    6776         592 :     else if (V != Value)
    6777             :       usesOnlyOneValue = false;
    6778             :   }
    6779             : 
    6780         645 :   if (!Value.getNode()) {
    6781             :     DEBUG(dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
    6782           0 :     return DAG.getUNDEF(VT);
    6783             :   }
    6784             : 
    6785         645 :   if (isOnlyLowElement) {
    6786             :     DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
    6787             :                     "SCALAR_TO_VECTOR node\n");
    6788         213 :     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
    6789             :   }
    6790             : 
    6791             :   // Use DUP for non-constant splats. For f32 constant splats, reduce to
    6792             :   // i32 and try again.
    6793         432 :   if (usesOnlyOneValue) {
    6794         161 :     if (!isConstant) {
    6795         304 :       if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
    6796          18 :           Value.getValueType() != VT) {
    6797             :         DEBUG(dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
    6798         152 :         return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
    6799             :       }
    6800             : 
    6801             :       // This is actually a DUPLANExx operation, which keeps everything vectory.
    6802             : 
    6803           0 :       SDValue Lane = Value.getOperand(1);
    6804           0 :       Value = Value.getOperand(0);
    6805           0 :       if (Value.getValueSizeInBits() == 64) {
    6806             :         DEBUG(dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
    6807             :                         "widening it\n");
    6808           0 :         Value = WidenVector(Value, DAG);
    6809             :       }
    6810             : 
    6811           0 :       unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
    6812           0 :       return DAG.getNode(Opcode, dl, VT, Value, Lane);
    6813             :     }
    6814             : 
    6815           9 :     if (VT.getVectorElementType().isFloatingPoint()) {
    6816           2 :       SmallVector<SDValue, 8> Ops;
    6817           2 :       EVT EltTy = VT.getVectorElementType();
    6818             :       assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
    6819             :               "Unsupported floating-point vector type");
    6820             :       DEBUG(dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
    6821             :                       "BITCASTS, and try again\n");
    6822           2 :       MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
    6823          10 :       for (unsigned i = 0; i < NumElts; ++i)
    6824          24 :         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
    6825           2 :       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
    6826           2 :       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
    6827             :       DEBUG(
    6828             :         dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
    6829             :         Val.dump();
    6830             :       );
    6831           2 :       Val = LowerBUILD_VECTOR(Val, DAG);
    6832           2 :       if (Val.getNode())
    6833           2 :         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
    6834             :     }
    6835             :   }
    6836             : 
    6837             :   // If there was only one constant value used and for more than one lane,
    6838             :   // start by splatting that value, then replace the non-constant lanes. This
    6839             :   // is better than the default, which will perform a separate initialization
    6840             :   // for each lane.
    6841         278 :   if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
    6842          10 :     SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
    6843             :     // Now insert the non-constant lanes.
    6844          66 :     for (unsigned i = 0; i < NumElts; ++i) {
    6845         112 :       SDValue V = Op.getOperand(i);
    6846          56 :       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
    6847          12 :       if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
    6848             :         // Note that type legalization likely mucked about with the VT of the
    6849             :         // source operand, so we may have to convert it here before inserting.
    6850           3 :         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
    6851             :       }
    6852             :     }
    6853          10 :     return Val;
    6854             :   }
    6855             : 
    6856             :   // This will generate a load from the constant pool.
    6857         268 :   if (isConstant) {
    6858             :     DEBUG(dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
    6859             :                     "expansion\n");
    6860          56 :     return SDValue();
    6861             :   }
    6862             : 
    6863             :   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
    6864         212 :   if (NumElts >= 4) {
    6865         124 :     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
    6866           3 :       return shuffle;
    6867             :   }
    6868             : 
    6869             :   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
    6870             :   // know the default expansion would otherwise fall back on something even
    6871             :   // worse. For a vector with one or two non-undef values, that's
    6872             :   // scalar_to_vector for the elements followed by a shuffle (provided the
    6873             :   // shuffle is valid for the target) and materialization element by element
    6874             :   // on the stack followed by a load for everything else.
    6875         209 :   if (!isConstant && !usesOnlyOneValue) {
    6876             :     DEBUG(dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
    6877             :                     "of INSERT_VECTOR_ELT\n");
    6878             : 
    6879         209 :     SDValue Vec = DAG.getUNDEF(VT);
    6880         418 :     SDValue Op0 = Op.getOperand(0);
    6881         209 :     unsigned i = 0;
    6882             : 
    6883             :     // Use SCALAR_TO_VECTOR for lane zero to
    6884             :     // a) Avoid a RMW dependency on the full vector register, and
    6885             :     // b) Allow the register coalescer to fold away the copy if the
    6886             :     //    value is already in an S or D register, and we're forced to emit an
    6887             :     //    INSERT_SUBREG that we can't fold anywhere.
    6888             :     //
    6889             :     // We also allow types like i8 and i16 which are illegal scalar but legal
    6890             :     // vector element types. After type-legalization the inserted value is
    6891             :     // extended (i32) and it is safe to cast them to the vector type by ignoring
    6892             :     // the upper bits of the lowest lane (e.g. v8i8, v4i16).
    6893         418 :     if (!Op0.isUndef()) {
    6894             :       DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
    6895         209 :       Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
    6896         209 :       ++i;
    6897             :     }
    6898             :     DEBUG(
    6899             :       if (i < NumElts)
    6900             :         dbgs() << "Creating nodes for the other vector elements:\n";
    6901             :     );
    6902        1463 :     for (; i < NumElts; ++i) {
    6903        1254 :       SDValue V = Op.getOperand(i);
    6904        1254 :       if (V.isUndef())
    6905           1 :         continue;
    6906         626 :       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
    6907         626 :       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
    6908             :     }
    6909         209 :     return Vec;
    6910             :   }
    6911             : 
    6912             :   DEBUG(dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
    6913             :                   "better alternative\n");
    6914           0 :   return SDValue();
    6915             : }
    6916             : 
    6917        1812 : SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
    6918             :                                                       SelectionDAG &DAG) const {
    6919             :   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
    6920             : 
    6921             :   // Check for non-constant or out of range lane.
    6922        5436 :   EVT VT = Op.getOperand(0).getValueType();
    6923        5434 :   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
    6924        1810 :   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
    6925           2 :     return SDValue();
    6926             : 
    6927             : 
    6928             :   // Insertion/extraction are legal for V128 types.
    6929        4310 :   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
    6930        2070 :       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
    6931         447 :       VT == MVT::v8f16)
    6932        1519 :     return Op;
    6933             : 
    6934         620 :   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
    6935         189 :       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
    6936           2 :     return SDValue();
    6937             : 
    6938             :   // For V64 types, we perform insertion by expanding the value
    6939             :   // to a V128 type and perform the insertion on that.
    6940         289 :   SDLoc DL(Op);
    6941         578 :   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
    6942         578 :   EVT WideTy = WideVec.getValueType();
    6943             : 
    6944             :   SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
    6945         867 :                              Op.getOperand(1), Op.getOperand(2));
    6946             :   // Re-narrow the resultant vector.
    6947         289 :   return NarrowVector(Node, DAG);
    6948             : }
    6949             : 
    6950             : SDValue
    6951        4545 : AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
    6952             :                                                SelectionDAG &DAG) const {
    6953             :   assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
    6954             : 
    6955             :   // Check for non-constant or out of range lane.
    6956       13635 :   EVT VT = Op.getOperand(0).getValueType();
    6957       13632 :   ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
    6958        4542 :   if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
    6959           3 :     return SDValue();
    6960             : 
    6961             : 
    6962             :   // Insertion/extraction are legal for V128 types.
    6963       11827 :   if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
    6964        7599 :       VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
    6965        1902 :       VT == MVT::v8f16)
    6966        3788 :     return Op;
    6967             : 
    6968        1931 :   if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
    6969        1209 :       VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
    6970          56 :     return SDValue();
    6971             : 
    6972             :   // For V64 types, we perform extraction by expanding the value
    6973             :   // to a V128 type and perform the extraction on that.
    6974         698 :   SDLoc DL(Op);
    6975        1396 :   SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
    6976        1396 :   EVT WideTy = WideVec.getValueType();
    6977             : 
    6978         698 :   EVT ExtrTy = WideTy.getVectorElementType();
    6979        1285 :   if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
    6980         221 :     ExtrTy = MVT::i32;
    6981             : 
    6982             :   // For extractions, we just return the result directly.
    6983             :   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
    6984        1396 :                      Op.getOperand(1));
    6985             : }
    6986             : 
    6987        1356 : SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
    6988             :                                                       SelectionDAG &DAG) const {
    6989        4068 :   EVT VT = Op.getOperand(0).getValueType();
    6990        2712 :   SDLoc dl(Op);
    6991             :   // Just in case...
    6992        1356 :   if (!VT.isVector())
    6993           0 :     return SDValue();
    6994             : 
    6995        4068 :   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
    6996             :   if (!Cst)
    6997           0 :     return SDValue();
    6998        1356 :   unsigned Val = Cst->getZExtValue();
    6999             : 
    7000        1356 :   unsigned Size = Op.getValueSizeInBits();
    7001             : 
    7002             :   // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
    7003        1356 :   if (Val == 0)
    7004         246 :     return Op;
    7005             : 
    7006             :   // If this is extracting the upper 64-bits of a 128-bit vector, we match
    7007             :   // that directly.
    7008        2220 :   if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
    7009        1110 :     return Op;
    7010             : 
    7011           0 :   return SDValue();
    7012             : }
    7013             : 
    7014          49 : bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
    7015          58 :   if (VT.getVectorNumElements() == 4 &&
    7016          15 :       (VT.is128BitVector() || VT.is64BitVector())) {
    7017             :     unsigned PFIndexes[4];
    7018             :     for (unsigned i = 0; i != 4; ++i) {
    7019             :       if (M[i] < 0)
    7020             :         PFIndexes[i] = 8;
    7021             :       else
    7022             :         PFIndexes[i] = M[i];
    7023             :     }
    7024             : 
    7025             :     // Compute the index in the perfect shuffle table.
    7026             :     unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
    7027             :                             PFIndexes[2] * 9 + PFIndexes[3];
    7028             :     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
    7029             :     unsigned Cost = (PFEntry >> 30);
    7030             : 
    7031             :     if (Cost <= 4)
    7032             :       return true;
    7033             :   }
    7034             : 
    7035             :   bool DummyBool;
    7036             :   int DummyInt;
    7037             :   unsigned DummyUnsigned;
    7038             : 
    7039          98 :   return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
    7040          85 :           isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
    7041          53 :           isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
    7042             :           // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
    7043          37 :           isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
    7044          11 :           isZIPMask(M, VT, DummyUnsigned) ||
    7045          10 :           isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
    7046          10 :           isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
    7047          10 :           isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
    7048          50 :           isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
    7049           5 :           isConcatMask(M, VT, VT.getSizeInBits() == 128));
    7050             : }
    7051             : 
    7052             : /// getVShiftImm - Check if this is a valid build_vector for the immediate
    7053             : /// operand of a vector shift operation, where all the elements of the
    7054             : /// build_vector must have the same constant integer value.
    7055         213 : static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
    7056             :   // Ignore bit_converts.
    7057         426 :   while (Op.getOpcode() == ISD::BITCAST)
    7058           0 :     Op = Op.getOperand(0);
    7059         426 :   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
    7060         852 :   APInt SplatBits, SplatUndef;
    7061             :   unsigned SplatBitSize;
    7062             :   bool HasAnyUndefs;
    7063         209 :   if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
    7064         422 :                                     HasAnyUndefs, ElementBits) ||
    7065         209 :       SplatBitSize > ElementBits)
    7066             :     return false;
    7067         209 :   Cnt = SplatBits.getSExtValue();
    7068             :   return true;
    7069             : }
    7070             : 
    7071             : /// isVShiftLImm - Check if this is a valid build_vector for the immediate
    7072             : /// operand of a vector shift left operation.  That value must be in the range:
    7073             : ///   0 <= Value < ElementBits for a left shift; or
    7074             : ///   0 <= Value <= ElementBits for a long left shift.
    7075          51 : static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
    7076             :   assert(VT.isVector() && "vector shift count is not a vector type");
    7077          51 :   int64_t ElementBits = VT.getScalarSizeInBits();
    7078          51 :   if (!getVShiftImm(Op, ElementBits, Cnt))
    7079             :     return false;
    7080          51 :   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
    7081             : }
    7082             : 
    7083             : /// isVShiftRImm - Check if this is a valid build_vector for the immediate
    7084             : /// operand of a vector shift right operation. The value must be in the range:
    7085             : ///   1 <= Value <= ElementBits for a right shift; or
    7086         162 : static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
    7087             :   assert(VT.isVector() && "vector shift count is not a vector type");
    7088         162 :   int64_t ElementBits = VT.getScalarSizeInBits();
    7089         162 :   if (!getVShiftImm(Op, ElementBits, Cnt))
    7090             :     return false;
    7091         158 :   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
    7092             : }
    7093             : 
    7094         213 : SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
    7095             :                                                       SelectionDAG &DAG) const {
    7096         426 :   EVT VT = Op.getValueType();
    7097         426 :   SDLoc DL(Op);
    7098             :   int64_t Cnt;
    7099             : 
    7100         852 :   if (!Op.getOperand(1).getValueType().isVector())
    7101           0 :     return Op;
    7102         213 :   unsigned EltSize = VT.getScalarSizeInBits();
    7103             : 
    7104         426 :   switch (Op.getOpcode()) {
    7105           0 :   default:
    7106           0 :     llvm_unreachable("unexpected shift opcode");
    7107             : 
    7108          51 :   case ISD::SHL:
    7109         102 :     if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
    7110         102 :       return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
    7111         153 :                          DAG.getConstant(Cnt, DL, MVT::i32));
    7112             :     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
    7113             :                        DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
    7114           0 :                                        MVT::i32),
    7115           0 :                        Op.getOperand(0), Op.getOperand(1));
    7116         162 :   case ISD::SRA:
    7117             :   case ISD::SRL:
    7118             :     // Right shift immediate
    7119         324 :     if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
    7120             :       unsigned Opc =
    7121         316 :           (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
    7122         316 :       return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
    7123         474 :                          DAG.getConstant(Cnt, DL, MVT::i32));
    7124             :     }
    7125             : 
    7126             :     // Right shift register.  Note, there is not a shift right register
    7127             :     // instruction, but the shift left register instruction takes a signed
    7128             :     // value, where negative numbers specify a right shift.
    7129           8 :     unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
    7130           4 :                                                 : Intrinsic::aarch64_neon_ushl;
    7131             :     // negate the shift amount
    7132           8 :     SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
    7133             :     SDValue NegShiftLeft =
    7134             :         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
    7135          12 :                     DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
    7136           4 :                     NegShift);
    7137           4 :     return NegShiftLeft;
    7138             :   }
    7139             : 
    7140             :   return SDValue();
    7141             : }
    7142             : 
    7143         482 : static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
    7144             :                                     AArch64CC::CondCode CC, bool NoNans, EVT VT,
    7145             :                                     const SDLoc &dl, SelectionDAG &DAG) {
    7146         964 :   EVT SrcVT = LHS.getValueType();
    7147             :   assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
    7148             :          "function only supposed to emit natural comparisons");
    7149             : 
    7150         964 :   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
    7151        1446 :   APInt CnstBits(VT.getSizeInBits(), 0);
    7152        1446 :   APInt UndefBits(VT.getSizeInBits(), 0);
    7153         482 :   bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
    7154         235 :   bool IsZero = IsCnst && (CnstBits == 0);
    7155             : 
    7156         482 :   if (SrcVT.getVectorElementType().isFloatingPoint()) {
    7157         146 :     switch (CC) {
    7158           0 :     default:
    7159           0 :       return SDValue();
    7160           6 :     case AArch64CC::NE: {
    7161           6 :       SDValue Fcmeq;
    7162           6 :       if (IsZero)
    7163           3 :         Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
    7164             :       else
    7165           3 :         Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
    7166           6 :       return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
    7167             :     }
    7168          31 :     case AArch64CC::EQ:
    7169          31 :       if (IsZero)
    7170          11 :         return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
    7171          20 :       return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
    7172          26 :     case AArch64CC::GE:
    7173          26 :       if (IsZero)
    7174          13 :         return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
    7175          13 :       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
    7176          27 :     case AArch64CC::GT:
    7177          27 :       if (IsZero)
    7178          13 :         return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
    7179          14 :       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
    7180          14 :     case AArch64CC::LS:
    7181          14 :       if (IsZero)
    7182           7 :         return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
    7183           7 :       return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
    7184           0 :     case AArch64CC::LT:
    7185           0 :       if (!NoNans)
    7186           0 :         return SDValue();
    7187             :       // If we ignore NaNs then we can use to the MI implementation.
    7188             :       LLVM_FALLTHROUGH;
    7189             :     case AArch64CC::MI:
    7190          42 :       if (IsZero)
    7191          20 :         return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
    7192          22 :       return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
    7193             :     }
    7194             :   }
    7195             : 
    7196         336 :   switch (CC) {
    7197           0 :   default:
    7198           0 :     return SDValue();
    7199          46 :   case AArch64CC::NE: {
    7200          46 :     SDValue Cmeq;
    7201          46 :     if (IsZero)
    7202          31 :       Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
    7203             :     else
    7204          15 :       Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
    7205          46 :     return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
    7206             :   }
    7207          58 :   case AArch64CC::EQ:
    7208          58 :     if (IsZero)
    7209          19 :       return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
    7210          39 :     return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
    7211          30 :   case AArch64CC::GE:
    7212          30 :     if (IsZero)
    7213          15 :       return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
    7214          15 :     return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
    7215          29 :   case AArch64CC::GT:
    7216          29 :     if (IsZero)
    7217          15 :       return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
    7218          14 :     return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
    7219          29 :   case AArch64CC::LE:
    7220          29 :     if (IsZero)
    7221          15 :       return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
    7222          14 :     return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
    7223          28 :   case AArch64CC::LS:
    7224          28 :     return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
    7225          28 :   case AArch64CC::LO:
    7226          28 :     return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
    7227          30 :   case AArch64CC::LT:
    7228          30 :     if (IsZero)
    7229          15 :       return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
    7230          15 :     return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
    7231          29 :   case AArch64CC::HI:
    7232          29 :     return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
    7233          29 :   case AArch64CC::HS:
    7234          29 :     return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
    7235             :   }
    7236             : }
    7237             : 
    7238         499 : SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
    7239             :                                            SelectionDAG &DAG) const {
    7240        1497 :   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
    7241         998 :   SDValue LHS = Op.getOperand(0);
    7242         998 :   SDValue RHS = Op.getOperand(1);
    7243         998 :   EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
    7244         998 :   SDLoc dl(Op);
    7245             : 
    7246         998 :   if (LHS.getValueType().getVectorElementType().isInteger()) {
    7247             :     assert(LHS.getValueType() == RHS.getValueType());
    7248         336 :     AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
    7249             :     SDValue Cmp =
    7250         336 :         EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
    7251         672 :     return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
    7252             :   }
    7253             : 
    7254         489 :   if (LHS.getValueType().getVectorElementType() == MVT::f16)
    7255          42 :     return SDValue();
    7256             : 
    7257             :   assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
    7258             :          LHS.getValueType().getVectorElementType() == MVT::f64);
    7259             : 
    7260             :   // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
    7261             :   // clean.  Some of them require two branches to implement.
    7262             :   AArch64CC::CondCode CC1, CC2;
    7263             :   bool ShouldInvert;
    7264         121 :   changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
    7265             : 
    7266         121 :   bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
    7267             :   SDValue Cmp =
    7268         121 :       EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
    7269         121 :   if (!Cmp.getNode())
    7270           0 :     return SDValue();
    7271             : 
    7272         121 :   if (CC2 != AArch64CC::AL) {
    7273             :     SDValue Cmp2 =
    7274          25 :         EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
    7275          25 :     if (!Cmp2.getNode())
    7276           0 :       return SDValue();
    7277             : 
    7278          25 :     Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
    7279             :   }
    7280             : 
    7281         242 :   Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
    7282             : 
    7283         121 :   if (ShouldInvert)
    7284          72 :     return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
    7285             : 
    7286          85 :   return Cmp;
    7287             : }
    7288             : 
    7289          29 : static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
    7290             :                                   SelectionDAG &DAG) {
    7291          58 :   SDValue VecOp = ScalarOp.getOperand(0);
    7292          87 :   auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
    7293             :   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
    7294          87 :                      DAG.getConstant(0, DL, MVT::i64));
    7295             : }
    7296             : 
    7297          31 : SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
    7298             :                                               SelectionDAG &DAG) const {
    7299          62 :   SDLoc dl(Op);
    7300          62 :   switch (Op.getOpcode()) {
    7301           9 :   case ISD::VECREDUCE_ADD:
    7302          18 :     return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
    7303           5 :   case ISD::VECREDUCE_SMAX:
    7304          10 :     return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
    7305           5 :   case ISD::VECREDUCE_SMIN:
    7306          10 :     return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
    7307           5 :   case ISD::VECREDUCE_UMAX:
    7308          10 :     return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
    7309           5 :   case ISD::VECREDUCE_UMIN:
    7310          10 :     return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
    7311           1 :   case ISD::VECREDUCE_FMAX: {
    7312             :     assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
    7313             :     return DAG.getNode(
    7314             :         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
    7315           1 :         DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
    7316           4 :         Op.getOperand(0));
    7317             :   }
    7318           1 :   case ISD::VECREDUCE_FMIN: {
    7319             :     assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
    7320             :     return DAG.getNode(
    7321             :         ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
    7322           1 :         DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
    7323           4 :         Op.getOperand(0));
    7324             :   }
    7325           0 :   default:
    7326           0 :     llvm_unreachable("Unhandled reduction");
    7327             :   }
    7328             : }
    7329             : 
    7330             : /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
    7331             : /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
    7332             : /// specified in the intrinsic calls.
    7333        3764 : bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
    7334             :                                                const CallInst &I,
    7335             :                                                unsigned Intrinsic) const {
    7336        3764 :   auto &DL = I.getModule()->getDataLayout();
    7337        3764 :   switch (Intrinsic) {
    7338         434 :   case Intrinsic::aarch64_neon_ld2:
    7339             :   case Intrinsic::aarch64_neon_ld3:
    7340             :   case Intrinsic::aarch64_neon_ld4:
    7341             :   case Intrinsic::aarch64_neon_ld1x2:
    7342             :   case Intrinsic::aarch64_neon_ld1x3:
    7343             :   case Intrinsic::aarch64_neon_ld1x4:
    7344             :   case Intrinsic::aarch64_neon_ld2lane:
    7345             :   case Intrinsic::aarch64_neon_ld3lane:
    7346             :   case Intrinsic::aarch64_neon_ld4lane:
    7347             :   case Intrinsic::aarch64_neon_ld2r:
    7348             :   case Intrinsic::aarch64_neon_ld3r:
    7349             :   case Intrinsic::aarch64_neon_ld4r: {
    7350         434 :     Info.opc = ISD::INTRINSIC_W_CHAIN;
    7351             :     // Conservatively set memVT to the entire set of vectors loaded.
    7352         434 :     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
    7353         868 :     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
    7354         868 :     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
    7355         434 :     Info.offset = 0;
    7356         434 :     Info.align = 0;
    7357         434 :     Info.vol = false; // volatile loads with NEON intrinsics not supported
    7358         434 :     Info.readMem = true;
    7359         434 :     Info.writeMem = false;
    7360         434 :     return true;
    7361             :   }
    7362         329 :   case Intrinsic::aarch64_neon_st2:
    7363             :   case Intrinsic::aarch64_neon_st3:
    7364             :   case Intrinsic::aarch64_neon_st4:
    7365             :   case Intrinsic::aarch64_neon_st1x2:
    7366             :   case Intrinsic::aarch64_neon_st1x3:
    7367             :   case Intrinsic::aarch64_neon_st1x4:
    7368             :   case Intrinsic::aarch64_neon_st2lane:
    7369             :   case Intrinsic::aarch64_neon_st3lane:
    7370             :   case Intrinsic::aarch64_neon_st4lane: {
    7371         329 :     Info.opc = ISD::INTRINSIC_VOID;
    7372             :     // Conservatively set memVT to the entire set of vectors stored.
    7373         329 :     unsigned NumElts = 0;
    7374        1304 :     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
    7375         975 :       Type *ArgTy = I.getArgOperand(ArgI)->getType();
    7376         975 :       if (!ArgTy->isVectorTy())
    7377             :         break;
    7378         646 :       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
    7379             :     }
    7380         329 :     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
    7381         658 :     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
    7382         329 :     Info.offset = 0;
    7383         329 :     Info.align = 0;
    7384         329 :     Info.vol = false; // volatile stores with NEON intrinsics not supported
    7385         329 :     Info.readMem = false;
    7386         329 :     Info.writeMem = true;
    7387         329 :     return true;
    7388             :   }
    7389         111 :   case Intrinsic::aarch64_ldaxr:
    7390             :   case Intrinsic::aarch64_ldxr: {
    7391         222 :     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
    7392         111 :     Info.opc = ISD::INTRINSIC_W_CHAIN;
    7393         111 :     Info.memVT = MVT::getVT(PtrTy->getElementType());
    7394         111 :     Info.ptrVal = I.getArgOperand(0);
    7395         111 :     Info.offset = 0;
    7396         111 :     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
    7397         111 :     Info.vol = true;
    7398         111 :     Info.readMem = true;
    7399         111 :     Info.writeMem = false;
    7400         111 :     return true;
    7401             :   }
    7402         110 :   case Intrinsic::aarch64_stlxr:
    7403             :   case Intrinsic::aarch64_stxr: {
    7404         220 :     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
    7405         110 :     Info.opc = ISD::INTRINSIC_W_CHAIN;
    7406         110 :     Info.memVT = MVT::getVT(PtrTy->getElementType());
    7407         110 :     Info.ptrVal = I.getArgOperand(1);
    7408         110 :     Info.offset = 0;
    7409         110 :     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
    7410         110 :     Info.vol = true;
    7411         110 :     Info.readMem = false;
    7412         110 :     Info.writeMem = true;
    7413         110 :     return true;
    7414             :   }
    7415          16 :   case Intrinsic::aarch64_ldaxp:
    7416             :   case Intrinsic::aarch64_ldxp:
    7417          16 :     Info.opc = ISD::INTRINSIC_W_CHAIN;
    7418          16 :     Info.memVT = MVT::i128;
    7419          16 :     Info.ptrVal = I.getArgOperand(0);
    7420          16 :     Info.offset = 0;
    7421          16 :     Info.align = 16;
    7422          16 :     Info.vol = true;
    7423          16 :     Info.readMem = true;
    7424          16 :     Info.writeMem = false;
    7425          16 :     return true;
    7426          16 :   case Intrinsic::aarch64_stlxp:
    7427             :   case Intrinsic::aarch64_stxp:
    7428          16 :     Info.opc = ISD::INTRINSIC_W_CHAIN;
    7429          16 :     Info.memVT = MVT::i128;
    7430          16 :     Info.ptrVal = I.getArgOperand(2);
    7431          16 :     Info.offset = 0;
    7432          16 :     Info.align = 16;
    7433          16 :     Info.vol = true;
    7434          16 :     Info.readMem = false;
    7435          16 :     Info.writeMem = true;
    7436          16 :     return true;
    7437             :   default:
    7438             :     break;
    7439             :   }
    7440             : 
    7441             :   return false;
    7442             : }
    7443             : 
    7444             : // Truncations from 64-bit GPR to 32-bit GPR is free.
    7445         758 : bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
    7446        1396 :   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
    7447             :     return false;
    7448         638 :   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
    7449         638 :   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
    7450         638 :   return NumBits1 > NumBits2;
    7451             : }
    7452         716 : bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
    7453        1430 :   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
    7454             :     return false;
    7455         714 :   unsigned NumBits1 = VT1.getSizeInBits();
    7456         714 :   unsigned NumBits2 = VT2.getSizeInBits();
    7457         714 :   return NumBits1 > NumBits2;
    7458             : }
    7459             : 
    7460             : /// Check if it is profitable to hoist instruction in then/else to if.
    7461             : /// Not profitable if I and it's user can form a FMA instruction
    7462             : /// because we prefer FMSUB/FMADD.
    7463          15 : bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
    7464          15 :   if (I->getOpcode() != Instruction::FMul)
    7465             :     return true;
    7466             : 
    7467           6 :   if (!I->hasOneUse())
    7468             :     return true;
    7469             : 
    7470           3 :   Instruction *User = I->user_back();
    7471             : 
    7472           6 :   if (User &&
    7473           6 :       !(User->getOpcode() == Instruction::FSub ||
    7474           3 :         User->getOpcode() == Instruction::FAdd))
    7475             :     return true;
    7476             : 
    7477           3 :   const TargetOptions &Options = getTargetMachine().Options;
    7478           3 :   const DataLayout &DL = I->getModule()->getDataLayout();
    7479           6 :   EVT VT = getValueType(DL, User->getOperand(0)->getType());
    7480             : 
    7481           6 :   return !(isFMAFasterThanFMulAndFAdd(VT) &&
    7482           3 :            isOperationLegalOrCustom(ISD::FMA, VT) &&
    7483           6 :            (Options.AllowFPOpFusion == FPOpFusion::Fast ||
    7484           3 :             Options.UnsafeFPMath));
    7485             : }
    7486             : 
    7487             : // All 32-bit GPR operations implicitly zero the high-half of the corresponding
    7488             : // 64-bit GPR.
    7489         271 : bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
    7490         542 :   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
    7491             :     return false;
    7492         271 :   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
    7493         271 :   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
    7494         271 :   return NumBits1 == 32 && NumBits2 == 64;
    7495             : }
    7496        2609 : bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
    7497        4675 :   if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
    7498             :     return false;
    7499        1946 :   unsigned NumBits1 = VT1.getSizeInBits();
    7500        1946 :   unsigned NumBits2 = VT2.getSizeInBits();
    7501        1946 :   return NumBits1 == 32 && NumBits2 == 64;
    7502             : }
    7503             : 
    7504        1873 : bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
    7505        3746 :   EVT VT1 = Val.getValueType();
    7506        1873 :   if (isZExtFree(VT1, VT2)) {
    7507             :     return true;
    7508             :   }
    7509             : 
    7510        3746 :   if (Val.getOpcode() != ISD::LOAD)
    7511             :     return false;
    7512             : 
    7513             :   // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
    7514         886 :   return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
    7515        1013 :           VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
    7516         228 :           VT1.getSizeInBits() <= 32);
    7517             : }
    7518             : 
    7519         405 : bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
    7520         810 :   if (isa<FPExtInst>(Ext))
    7521             :     return false;
    7522             : 
    7523             :   // Vector types are not free.
    7524         810 :   if (Ext->getType()->isVectorTy())
    7525             :     return false;
    7526             : 
    7527        1323 :   for (const Use &U : Ext->uses()) {
    7528             :     // The extension is free if we can fold it with a left shift in an
    7529             :     // addressing mode or an arithmetic operation: add, sub, and cmp.
    7530             : 
    7531             :     // Is there a shift?
    7532         836 :     const Instruction *Instr = cast<Instruction>(U.getUser());
    7533             : 
    7534             :     // Is this a constant shift?
    7535         418 :     switch (Instr->getOpcode()) {
    7536          23 :     case Instruction::Shl:
    7537          69 :       if (!isa<ConstantInt>(Instr->getOperand(1)))
    7538             :         return false;
    7539             :       break;
    7540         111 :     case Instruction::GetElementPtr: {
    7541         111 :       gep_type_iterator GTI = gep_type_begin(Instr);
    7542         111 :       auto &DL = Ext->getModule()->getDataLayout();
    7543         222 :       std::advance(GTI, U.getOperandNo()-1);
    7544         111 :       Type *IdxTy = GTI.getIndexedType();
    7545             :       // This extension will end up with a shift because of the scaling factor.
    7546             :       // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
    7547             :       // Get the shift amount based on the scaling factor:
    7548             :       // log2(sizeof(IdxTy)) - log2(8).
    7549             :       uint64_t ShiftAmt =
    7550         222 :           countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
    7551             :       // Is the constant foldable in the shift of the addressing mode?
    7552             :       // I.e., shift amount is between 1 and 4 inclusive.
    7553         111 :       if (ShiftAmt == 0 || ShiftAmt > 4)
    7554          26 :         return false;
    7555          85 :       break;
    7556             :     }
    7557           0 :     case Instruction::Trunc:
    7558             :       // Check if this is a noop.
    7559             :       // trunc(sext ty1 to ty2) to ty1.
    7560           0 :       if (Instr->getType() == Ext->getOperand(0)->getType())
    7561           0 :         continue;
    7562             :       LLVM_FALLTHROUGH;
    7563             :     default:
    7564             :       return false;
    7565             :     }
    7566             : 
    7567             :     // At this point we can use the bfm family, so this extension is free
    7568             :     // for that use.
    7569             :   }
    7570             :   return true;
    7571             : }
    7572             : 
    7573          62 : bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
    7574             :                                           unsigned &RequiredAligment) const {
    7575         124 :   if (!LoadedType.isSimple() ||
    7576          82 :       (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
    7577             :     return false;
    7578             :   // Cyclone supports unaligned accesses.
    7579          62 :   RequiredAligment = 0;
    7580          62 :   unsigned NumBits = LoadedType.getSizeInBits();
    7581          62 :   return NumBits == 32 || NumBits == 64;
    7582             : }
    7583             : 
    7584             : /// A helper function for determining the number of interleaved accesses we
    7585             : /// will generate when lowering accesses of the given type.
    7586             : unsigned
    7587          42 : AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
    7588             :                                                  const DataLayout &DL) const {
    7589          42 :   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
    7590             : }
    7591             : 
    7592             : MachineMemOperand::Flags
    7593        8079 : AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
    7594        8087 :   if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
    7595          24 :       I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
    7596             :     return MOStridedAccess;
    7597             :   return MachineMemOperand::MONone;
    7598             : }
    7599             : 
    7600          52 : bool AArch64TargetLowering::isLegalInterleavedAccessType(
    7601             :     VectorType *VecTy, const DataLayout &DL) const {
    7602             : 
    7603          52 :   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
    7604          52 :   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
    7605             : 
    7606             :   // Ensure the number of vector elements is greater than 1.
    7607          52 :   if (VecTy->getNumElements() < 2)
    7608             :     return false;
    7609             : 
    7610             :   // Ensure the element type is legal.
    7611          44 :   if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
    7612             :     return false;
    7613             : 
    7614             :   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
    7615             :   // 128 will be split into multiple interleaved accesses.
    7616          43 :   return VecSize == 64 || VecSize % 128 == 0;
    7617             : }
    7618             : 
    7619             : /// \brief Lower an interleaved load into a ldN intrinsic.
    7620             : ///
    7621             : /// E.g. Lower an interleaved load (Factor = 2):
    7622             : ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr
    7623             : ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
    7624             : ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
    7625             : ///
    7626             : ///      Into:
    7627             : ///        %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
    7628             : ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
    7629             : ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
    7630          34 : bool AArch64TargetLowering::lowerInterleavedLoad(
    7631             :     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
    7632             :     ArrayRef<unsigned> Indices, unsigned Factor) const {
    7633             :   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
    7634             :          "Invalid interleave factor");
    7635             :   assert(!Shuffles.empty() && "Empty shufflevector input");
    7636             :   assert(Shuffles.size() == Indices.size() &&
    7637             :          "Unmatched number of shufflevectors and indices");
    7638             : 
    7639          68 :   const DataLayout &DL = LI->getModule()->getDataLayout();
    7640             : 
    7641          68 :   VectorType *VecTy = Shuffles[0]->getType();
    7642             : 
    7643             :   // Skip if we do not have NEON and skip illegal vector types. We can
    7644             :   // "legalize" wide vector types into multiple interleaved accesses as long as
    7645             :   // the vector types are divisible by 128.
    7646          34 :   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
    7647             :     return false;
    7648             : 
    7649          16 :   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
    7650             : 
    7651             :   // A pointer vector can not be the return type of the ldN intrinsics. Need to
    7652             :   // load integer vectors first and then convert to pointer vectors.
    7653          32 :   Type *EltTy = VecTy->getVectorElementType();
    7654          16 :   if (EltTy->isPointerTy())
    7655           4 :     VecTy =
    7656           8 :         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
    7657             : 
    7658          16 :   IRBuilder<> Builder(LI);
    7659             : 
    7660             :   // The base address of the load.
    7661          16 :   Value *BaseAddr = LI->getPointerOperand();
    7662             : 
    7663          16 :   if (NumLoads > 1) {
    7664             :     // If we're going to generate more than one load, reset the sub-vector type
    7665             :     // to something legal.
    7666          10 :     VecTy = VectorType::get(VecTy->getVectorElementType(),
    7667          10 :                             VecTy->getVectorNumElements() / NumLoads);
    7668             : 
    7669             :     // We will compute the pointer operand of each load from the original base
    7670             :     // address using GEPs. Cast the base address to a pointer to the scalar
    7671             :     // element type.
    7672          10 :     BaseAddr = Builder.CreateBitCast(
    7673          15 :         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
    7674             :                       LI->getPointerAddressSpace()));
    7675             :   }
    7676             : 
    7677          32 :   Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
    7678          16 :   Type *Tys[2] = {VecTy, PtrTy};
    7679             :   static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
    7680             :                                             Intrinsic::aarch64_neon_ld3,
    7681             :                                             Intrinsic::aarch64_neon_ld4};
    7682             :   Function *LdNFunc =
    7683          32 :       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
    7684             : 
    7685             :   // Holds sub-vectors extracted from the load intrinsic return values. The
    7686             :   // sub-vectors are associated with the shufflevector instructions they will
    7687             :   // replace.
    7688          32 :   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
    7689             : 
    7690          38 :   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
    7691             : 
    7692             :     // If we're generating more than one load, compute the base address of
    7693             :     // subsequent loads as an offset from the previous.
    7694          22 :     if (LoadCount > 0)
    7695          18 :       BaseAddr = Builder.CreateConstGEP1_32(
    7696          12 :           BaseAddr, VecTy->getVectorNumElements() * Factor);
    7697             : 
    7698          66 :     CallInst *LdN = Builder.CreateCall(
    7699          66 :         LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
    7700             : 
    7701             :     // Extract and store the sub-vectors returned by the load intrinsic.
    7702          79 :     for (unsigned i = 0; i < Shuffles.size(); i++) {
    7703         114 :       ShuffleVectorInst *SVI = Shuffles[i];
    7704         114 :       unsigned Index = Indices[i];
    7705             : 
    7706         114 :       Value *SubVec = Builder.CreateExtractValue(LdN, Index);
    7707             : 
    7708             :       // Convert the integer vector to pointer vector if the element is pointer.
    7709          57 :       if (EltTy->isPointerTy())
    7710          39 :         SubVec = Builder.CreateIntToPtr(
    7711          52 :             SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
    7712             :                                     VecTy->getVectorNumElements()));
    7713          57 :       SubVecs[SVI].push_back(SubVec);
    7714             :     }
    7715             :   }
    7716             : 
    7717             :   // Replace uses of the shufflevector instructions with the sub-vectors
    7718             :   // returned by the load intrinsic. If a shufflevector instruction is
    7719             :   // associated with more than one sub-vector, those sub-vectors will be
    7720             :   // concatenated into a single wide vector.
    7721          74 :   for (ShuffleVectorInst *SVI : Shuffles) {
    7722          42 :     auto &SubVec = SubVecs[SVI];
    7723             :     auto *WideVec =
    7724         126 :         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
    7725          42 :     SVI->replaceAllUsesWith(WideVec);
    7726             :   }
    7727             : 
    7728          16 :   return true;
    7729             : }
    7730             : 
    7731             : /// \brief Lower an interleaved store into a stN intrinsic.
    7732             : ///
    7733             : /// E.g. Lower an interleaved store (Factor = 3):
    7734             : ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
    7735             : ///                 <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
    7736             : ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
    7737             : ///
    7738             : ///      Into:
    7739             : ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
    7740             : ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
    7741             : ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
    7742             : ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
    7743             : ///
    7744             : /// Note that the new shufflevectors will be removed and we'll only generate one
    7745             : /// st3 instruction in CodeGen.
    7746             : ///
    7747             : /// Example for a more general valid mask (Factor 3). Lower:
    7748             : ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
    7749             : ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
    7750             : ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
    7751             : ///
    7752             : ///      Into:
    7753             : ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
    7754             : ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
    7755             : ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
    7756             : ///        call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
    7757          49 : bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
    7758             :                                                   ShuffleVectorInst *SVI,
    7759             :                                                   unsigned Factor) const {
    7760             :   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
    7761             :          "Invalid interleave factor");
    7762             : 
    7763          49 :   VectorType *VecTy = SVI->getType();
    7764             :   assert(VecTy->getVectorNumElements() % Factor == 0 &&
    7765             :          "Invalid interleaved store");
    7766             : 
    7767          98 :   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
    7768          98 :   Type *EltTy = VecTy->getVectorElementType();
    7769          49 :   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
    7770             : 
    7771          98 :   const DataLayout &DL = SI->getModule()->getDataLayout();
    7772             : 
    7773             :   // Skip if we do not have NEON and skip illegal vector types. We can
    7774             :   // "legalize" wide vector types into multiple interleaved accesses as long as
    7775             :   // the vector types are divisible by 128.
    7776          49 :   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
    7777             :     return false;
    7778             : 
    7779          20 :   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
    7780             : 
    7781          20 :   Value *Op0 = SVI->getOperand(0);
    7782          20 :   Value *Op1 = SVI->getOperand(1);
    7783          20 :   IRBuilder<> Builder(SI);
    7784             : 
    7785             :   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
    7786             :   // vectors to integer vectors.
    7787          20 :   if (EltTy->isPointerTy()) {
    7788           3 :     Type *IntTy = DL.getIntPtrType(EltTy);
    7789             :     unsigned NumOpElts =
    7790           9 :         dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
    7791             : 
    7792             :     // Convert to the corresponding integer vector.
    7793           3 :     Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
    7794           6 :     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
    7795           6 :     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
    7796             : 
    7797           3 :     SubVecTy = VectorType::get(IntTy, LaneLen);
    7798             :   }
    7799             : 
    7800             :   // The base address of the store.
    7801          20 :   Value *BaseAddr = SI->getPointerOperand();
    7802             : 
    7803          20 :   if (NumStores > 1) {
    7804             :     // If we're going to generate more than one store, reset the lane length
    7805             :     // and sub-vector type to something legal.
    7806           3 :     LaneLen /= NumStores;
    7807           6 :     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
    7808             : 
    7809             :     // We will compute the pointer operand of each store from the original base
    7810             :     // address using GEPs. Cast the base address to a pointer to the scalar
    7811             :     // element type.
    7812           6 :     BaseAddr = Builder.CreateBitCast(
    7813           9 :         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
    7814             :                       SI->getPointerAddressSpace()));
    7815             :   }
    7816             : 
    7817          40 :   auto Mask = SVI->getShuffleMask();
    7818             : 
    7819          40 :   Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
    7820          20 :   Type *Tys[2] = {SubVecTy, PtrTy};
    7821             :   static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
    7822             :                                              Intrinsic::aarch64_neon_st3,
    7823             :                                              Intrinsic::aarch64_neon_st4};
    7824             :   Function *StNFunc =
    7825          40 :       Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
    7826             : 
    7827          43 :   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
    7828             : 
    7829          46 :     SmallVector<Value *, 5> Ops;
    7830             : 
    7831             :     // Split the shufflevector operands into sub vectors for the new stN call.
    7832          97 :     for (unsigned i = 0; i < Factor; i++) {
    7833          74 :       unsigned IdxI = StoreCount * LaneLen * Factor + i;
    7834         148 :       if (Mask[IdxI] >= 0) {
    7835         130 :         Ops.push_back(Builder.CreateShuffleVector(
    7836         130 :             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
    7837             :       } else {
    7838             :         unsigned StartMask = 0;
    7839          23 :         for (unsigned j = 1; j < LaneLen; j++) {
    7840          13 :           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
    7841          26 :           if (Mask[IdxJ * Factor + IdxI] >= 0) {
    7842          12 :             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
    7843           6 :             break;
    7844             :           }
    7845             :         }
    7846             :         // Note: Filling undef gaps with random elements is ok, since
    7847             :         // those elements were being written anyway (with undefs).
    7848             :         // In the case of all undefs we're defaulting to using elems from 0
    7849             :         // Note: StartMask cannot be negative, it's checked in
    7850             :         // isReInterleaveMask
    7851          18 :         Ops.push_back(Builder.CreateShuffleVector(
    7852           9 :             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
    7853             :       }
    7854             :     }
    7855             : 
    7856             :     // If we generating more than one store, we compute the base address of
    7857             :     // subsequent stores as an offset from the previous.
    7858          23 :     if (StoreCount > 0)
    7859           6 :       BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
    7860             : 
    7861          46 :     Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
    7862          69 :     Builder.CreateCall(StNFunc, Ops);
    7863             :   }
    7864          20 :   return true;
    7865             : }
    7866             : 
    7867             : static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
    7868             :                        unsigned AlignCheck) {
    7869          62 :   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
    7870          20 :           (DstAlign == 0 || DstAlign % AlignCheck == 0));
    7871             : }
    7872             : 
    7873          60 : EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
    7874             :                                                unsigned SrcAlign, bool IsMemset,
    7875             :                                                bool ZeroMemset,
    7876             :                                                bool MemcpyStrSrc,
    7877             :                                                MachineFunction &MF) const {
    7878             :   // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
    7879             :   // instruction to materialize the v2i64 zero and one store (with restrictive
    7880             :   // addressing mode). Just do two i64 store of zero-registers.
    7881             :   bool Fast;
    7882          60 :   const Function *F = MF.getFunction();
    7883         149 :   if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
    7884          90 :       !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
    7885          48 :       (memOpAlign(SrcAlign, DstAlign, 16) ||
    7886         103 :        (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
    7887          28 :     return MVT::f128;
    7888             : 
    7889          32 :   if (Size >= 8 &&
    7890          36 :       (memOpAlign(SrcAlign, DstAlign, 8) ||
    7891          56 :        (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
    7892          29 :     return MVT::i64;
    7893             : 
    7894           3 :   if (Size >= 4 &&
    7895           6 :       (memOpAlign(SrcAlign, DstAlign, 4) ||
    7896           9 :        (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
    7897           2 :     return MVT::i32;
    7898             : 
    7899           1 :   return MVT::Other;
    7900             : }
    7901             : 
    7902             : // 12-bit optionally shifted immediates are legal for adds.
    7903        2232 : bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
    7904        2232 :   if (Immed == std::numeric_limits<int64_t>::min()) {
    7905             :     DEBUG(dbgs() << "Illegal add imm " << Immed << ": avoid UB for INT64_MIN\n");
    7906             :     return false;
    7907             :   }
    7908             :   // Same encoding for add/sub, just flip the sign.
    7909        2232 :   Immed = std::abs(Immed);
    7910        2314 :   bool IsLegal = ((Immed >> 12) == 0 ||
    7911         100 :                   ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
    7912             :   DEBUG(dbgs() << "Is " << Immed << " legal add imm: " <<
    7913             :         (IsLegal ? "yes" : "no") << "\n");
    7914             :   return IsLegal;
    7915             : }
    7916             : 
    7917             : // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
    7918             : // immediates is the same as for an add or a sub.
    7919        1937 : bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
    7920        1937 :   return isLegalAddImmediate(Immed);
    7921             : }
    7922             : 
    7923             : /// isLegalAddressingMode - Return true if the addressing mode represented
    7924             : /// by AM is legal for this target, for a load/store of the specified type.
    7925       25350 : bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
    7926             :                                                   const AddrMode &AM, Type *Ty,
    7927             :                                                   unsigned AS, Instruction *I) const {
    7928             :   // AArch64 has five basic addressing modes:
    7929             :   //  reg
    7930             :   //  reg + 9-bit signed offset
    7931             :   //  reg + SIZE_IN_BYTES * 12-bit unsigned offset
    7932             :   //  reg1 + reg2
    7933             :   //  reg + SIZE_IN_BYTES * reg
    7934             : 
    7935             :   // No global is ever allowed as a base.
    7936       25350 :   if (AM.BaseGV)
    7937             :     return false;
    7938             : 
    7939             :   // No reg+reg+imm addressing.
    7940       22746 :   if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
    7941             :     return false;
    7942             : 
    7943             :   // check reg + imm case:
    7944             :   // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
    7945       20753 :   uint64_t NumBytes = 0;
    7946       20753 :   if (Ty->isSized()) {
    7947       20723 :     uint64_t NumBits = DL.getTypeSizeInBits(Ty);
    7948       20723 :     NumBytes = NumBits / 8;
    7949          35 :     if (!isPowerOf2_64(NumBits))
    7950             :       NumBytes = 0;
    7951             :   }
    7952             : 
    7953       20753 :   if (!AM.Scale) {
    7954       14821 :     int64_t Offset = AM.BaseOffs;
    7955             : 
    7956             :     // 9-bit signed offset
    7957       14821 :     if (isInt<9>(Offset))
    7958             :       return true;
    7959             : 
    7960             :     // 12-bit unsigned offset
    7961         420 :     unsigned shift = Log2_64(NumBytes);
    7962         770 :     if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
    7963             :         // Must be a multiple of NumBytes (NumBytes is a power of 2)
    7964         350 :         (Offset >> shift) << shift == Offset)
    7965             :       return true;
    7966          77 :     return false;
    7967             :   }
    7968             : 
    7969             :   // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
    7970             : 
    7971        5932 :   return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
    7972             : }
    7973             : 
    7974        1188 : int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
    7975             :                                                 const AddrMode &AM, Type *Ty,
    7976             :                                                 unsigned AS) const {
    7977             :   // Scaling factors are not free at all.
    7978             :   // Operands                     | Rt Latency
    7979             :   // -------------------------------------------
    7980             :   // Rt, [Xn, Xm]                 | 4
    7981             :   // -------------------------------------------
    7982             :   // Rt, [Xn, Xm, lsl #imm]       | Rn: 4 Rm: 5
    7983             :   // Rt, [Xn, Wm, <extend> #imm]  |
    7984        1188 :   if (isLegalAddressingMode(DL, AM, Ty, AS))
    7985             :     // Scale represents reg2 * scale, thus account for 1 if
    7986             :     // it is not equal to 0 or 1.
    7987        1188 :     return AM.Scale != 0 && AM.Scale != 1;
    7988             :   return -1;
    7989             : }
    7990             : 
    7991        1607 : bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
    7992        1607 :   VT = VT.getScalarType();
    7993             : 
    7994        1607 :   if (!VT.isSimple())
    7995             :     return false;
    7996             : 
    7997        1607 :   switch (VT.getSimpleVT().SimpleTy) {
    7998             :   case MVT::f32:
    7999             :   case MVT::f64:
    8000             :     return true;
    8001             :   default:
    8002             :     break;
    8003             :   }
    8004             : 
    8005         123 :   return false;
    8006             : }
    8007             : 
    8008             : const MCPhysReg *
    8009          64 : AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
    8010             :   // LR is a callee-save register, but we must treat it as clobbered by any call
    8011             :   // site. Hence we include LR in the scratch registers, which are in turn added
    8012             :   // as implicit-defs for stackmaps and patchpoints.
    8013             :   static const MCPhysReg ScratchRegs[] = {
    8014             :     AArch64::X16, AArch64::X17, AArch64::LR, 0
    8015             :   };
    8016          64 :   return ScratchRegs;
    8017             : }
    8018             : 
    8019             : bool
    8020           2 : AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
    8021           4 :   EVT VT = N->getValueType(0);
    8022             :     // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
    8023             :     // it with shift to let it be lowered to UBFX.
    8024           6 :   if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
    8025           4 :       isa<ConstantSDNode>(N->getOperand(1))) {
    8026           2 :     uint64_t TruncMask = N->getConstantOperandVal(1);
    8027           4 :     if (isMask_64(TruncMask) &&
    8028           4 :       N->getOperand(0).getOpcode() == ISD::SRL &&
    8029           6 :       isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
    8030             :       return false;
    8031             :   }
    8032             :   return true;
    8033             : }
    8034             : 
    8035           8 : bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
    8036             :                                                               Type *Ty) const {
    8037             :   assert(Ty->isIntegerTy());
    8038             : 
    8039           8 :   unsigned BitSize = Ty->getPrimitiveSizeInBits();
    8040           8 :   if (BitSize == 0)
    8041             :     return false;
    8042             : 
    8043           8 :   int64_t Val = Imm.getSExtValue();
    8044          15 :   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
    8045             :     return true;
    8046             : 
    8047           6 :   if ((int64_t)Val < 0)
    8048           0 :     Val = ~Val;
    8049           6 :   if (BitSize == 32)
    8050           2 :     Val &= (1LL << 32) - 1;
    8051             : 
    8052          12 :   unsigned LZ = countLeadingZeros((uint64_t)Val);
    8053           6 :   unsigned Shift = (63 - LZ) / 16;
    8054             :   // MOVZ is free so return true for one or fewer MOVK.
    8055           6 :   return Shift < 3;
    8056             : }
    8057             : 
    8058             : /// Turn vector tests of the signbit in the form of:
    8059             : ///   xor (sra X, elt_size(X)-1), -1
    8060             : /// into:
    8061             : ///   cmge X, X, #0
    8062         388 : static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
    8063             :                                          const AArch64Subtarget *Subtarget) {
    8064         776 :   EVT VT = N->getValueType(0);
    8065         773 :   if (!Subtarget->hasNEON() || !VT.isVector())
    8066         106 :     return SDValue();
    8067             : 
    8068             :   // There must be a shift right algebraic before the xor, and the xor must be a
    8069             :   // 'not' operation.
    8070         564 :   SDValue Shift = N->getOperand(0);
    8071         564 :   SDValue Ones = N->getOperand(1);
    8072         578 :   if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
    8073           7 :       !ISD::isBuildVectorAllOnes(Ones.getNode()))
    8074         275 :     return SDValue();
    8075             : 
    8076             :   // The shift should be smearing the sign bit across each vector element.
    8077          21 :   auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
    8078          14 :   EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
    8079          14 :   if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
    8080           0 :     return SDValue();
    8081             : 
    8082          28 :   return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
    8083             : }
    8084             : 
    8085             : // Generate SUBS and CSEL for integer abs.
    8086         381 : static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
    8087         762 :   EVT VT = N->getValueType(0);
    8088             : 
    8089         762 :   SDValue N0 = N->getOperand(0);
    8090         762 :   SDValue N1 = N->getOperand(1);
    8091         762 :   SDLoc DL(N);
    8092             : 
    8093             :   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
    8094             :   // and change it to SUB and CSEL.
    8095        1143 :   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
    8096         409 :       N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
    8097         400 :       N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
    8098           9 :     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
    8099           6 :       if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
    8100             :         SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
    8101           6 :                                   N0.getOperand(0));
    8102             :         // Generate SUBS & CSEL.
    8103             :         SDValue Cmp =
    8104           3 :             DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
    8105           9 :                         N0.getOperand(0), DAG.getConstant(0, DL, VT));
    8106           6 :         return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
    8107           3 :                            DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
    8108          12 :                            SDValue(Cmp.getNode(), 1));
    8109             :       }
    8110         378 :   return SDValue();
    8111             : }
    8112             : 
    8113         655 : static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
    8114             :                                  TargetLowering::DAGCombinerInfo &DCI,
    8115             :                                  const AArch64Subtarget *Subtarget) {
    8116        1310 :   if (DCI.isBeforeLegalizeOps())
    8117         267 :     return SDValue();
    8118             : 
    8119         388 :   if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
    8120           7 :     return Cmp;
    8121             : 
    8122         381 :   return performIntegerAbsCombine(N, DAG);
    8123             : }
    8124             : 
    8125             : SDValue
    8126          16 : AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
    8127             :                                      SelectionDAG &DAG,
    8128             :                                      std::vector<SDNode *> *Created) const {
    8129          16 :   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
    8130          32 :   if (isIntDivCheap(N->getValueType(0), Attr))
    8131           2 :     return SDValue(N,0); // Lower SDIV as SDIV
    8132             : 
    8133             :   // fold (sdiv X, pow2)
    8134          28 :   EVT VT = N->getValueType(0);
    8135          64 :   if ((VT != MVT::i32 && VT != MVT::i64) ||
    8136          49 :       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
    8137           1 :     return SDValue();
    8138             : 
    8139          13 :   SDLoc DL(N);
    8140          26 :   SDValue N0 = N->getOperand(0);
    8141          13 :   unsigned Lg2 = Divisor.countTrailingZeros();
    8142          13 :   SDValue Zero = DAG.getConstant(0, DL, VT);
    8143          13 :   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
    8144             : 
    8145             :   // Add (N0 < 0) ? Pow2 - 1 : 0;
    8146          13 :   SDValue CCVal;
    8147          13 :   SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
    8148          13 :   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
    8149          13 :   SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
    8150             : 
    8151          13 :   if (Created) {
    8152          26 :     Created->push_back(Cmp.getNode());
    8153          26 :     Created->push_back(Add.getNode());
    8154          26 :     Created->push_back(CSel.getNode());
    8155             :   }
    8156             : 
    8157             :   // Divide by pow2.
    8158             :   SDValue SRA =
    8159          26 :       DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
    8160             : 
    8161             :   // If we're dividing by a positive value, we're done.  Otherwise, we must
    8162             :   // negate the result.
    8163          13 :   if (Divisor.isNonNegative())
    8164           9 :     return SRA;
    8165             : 
    8166           4 :   if (Created)
    8167           8 :     Created->push_back(SRA.getNode());
    8168           4 :   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
    8169             : }
    8170             : 
    8171        1097 : static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
    8172             :                                  TargetLowering::DAGCombinerInfo &DCI,
    8173             :                                  const AArch64Subtarget *Subtarget) {
    8174        2194 :   if (DCI.isBeforeLegalizeOps())
    8175         520 :     return SDValue();
    8176             : 
    8177             :   // The below optimizations require a constant RHS.
    8178        1563 :   if (!isa<ConstantSDNode>(N->getOperand(1)))
    8179         409 :     return SDValue();
    8180             : 
    8181         504 :   ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
    8182         168 :   const APInt &ConstValue = C->getAPIntValue();
    8183             : 
    8184             :   // Multiplication of a power of two plus/minus one can be done more
    8185             :   // cheaply as as shift+add/sub. For now, this is true unilaterally. If
    8186             :   // future CPUs have a cheaper MADD instruction, this may need to be
    8187             :   // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
    8188             :   // 64-bit is 5 cycles, so this is always a win.
    8189             :   // More aggressively, some multiplications N0 * C can be lowered to
    8190             :   // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
    8191             :   // e.g. 6=3*2=(2+1)*2.
    8192             :   // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
    8193             :   // which equals to (1+2)*16-(1+2).
    8194         336 :   SDValue N0 = N->getOperand(0);
    8195             :   // TrailingZeroes is used to test if the mul can be lowered to
    8196             :   // shift+add+shift.
    8197         168 :   unsigned TrailingZeroes = ConstValue.countTrailingZeros();
    8198         168 :   if (TrailingZeroes) {
    8199             :     // Conservatively do not lower to shift+add+shift if the mul might be
    8200             :     // folded into smul or umul.
    8201         207 :     if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
    8202          56 :                             isZeroExtended(N0.getNode(), DAG)))
    8203          12 :       return SDValue();
    8204             :     // Conservatively do not lower to shift+add+shift if the mul might be
    8205             :     // folded into madd or msub.
    8206         362 :     if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
    8207         162 :                            N->use_begin()->getOpcode() == ISD::SUB))
    8208          66 :       return SDValue();
    8209             :   }
    8210             :   // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
    8211             :   // and shift+add+shift.
    8212          90 :   APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
    8213             : 
    8214             :   unsigned ShiftAmt, AddSubOpc;
    8215             :   // Is the shifted value the LHS operand of the add/sub?
    8216          90 :   bool ShiftValUseIsN0 = true;
    8217             :   // Do we need to negate the result?
    8218          90 :   bool NegateResult = false;
    8219             : 
    8220          90 :   if (ConstValue.isNonNegative()) {
    8221             :     // (mul x, 2^N + 1) => (add (shl x, N), x)
    8222             :     // (mul x, 2^N - 1) => (sub (shl x, N), x)
    8223             :     // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
    8224         229 :     APInt SCVMinus1 = ShiftedConstValue - 1;
    8225         229 :     APInt CVPlus1 = ConstValue + 1;
    8226          70 :     if (SCVMinus1.isPowerOf2()) {
    8227          11 :       ShiftAmt = SCVMinus1.logBase2();
    8228          11 :       AddSubOpc = ISD::ADD;
    8229          59 :     } else if (CVPlus1.isPowerOf2()) {
    8230           8 :       ShiftAmt = CVPlus1.logBase2();
    8231           8 :       AddSubOpc = ISD::SUB;
    8232             :     } else
    8233          51 :       return SDValue();
    8234             :   } else {
    8235             :     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
    8236             :     // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
    8237         105 :     APInt CVNegPlus1 = -ConstValue + 1;
    8238         105 :     APInt CVNegMinus1 = -ConstValue - 1;
    8239          20 :     if (CVNegPlus1.isPowerOf2()) {
    8240           3 :       ShiftAmt = CVNegPlus1.logBase2();
    8241           3 :       AddSubOpc = ISD::SUB;
    8242           3 :       ShiftValUseIsN0 = false;
    8243          17 :     } else if (CVNegMinus1.isPowerOf2()) {
    8244           2 :       ShiftAmt = CVNegMinus1.logBase2();
    8245           2 :       AddSubOpc = ISD::ADD;
    8246           2 :       NegateResult = true;
    8247             :     } else
    8248          15 :       return SDValue();
    8249             :   }
    8250             : 
    8251          24 :   SDLoc DL(N);
    8252          48 :   EVT VT = N->getValueType(0);
    8253             :   SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
    8254          48 :                                    DAG.getConstant(ShiftAmt, DL, MVT::i64));
    8255             : 
    8256          24 :   SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
    8257          24 :   SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
    8258          24 :   SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
    8259             :   assert(!(NegateResult && TrailingZeroes) &&
    8260             :          "NegateResult and TrailingZeroes cannot both be true for now.");
    8261             :   // Negate the result.
    8262          24 :   if (NegateResult)
    8263           2 :     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
    8264             :   // Shift the result.
    8265          22 :   if (TrailingZeroes)
    8266             :     return DAG.getNode(ISD::SHL, DL, VT, Res,
    8267           8 :                        DAG.getConstant(TrailingZeroes, DL, MVT::i64));
    8268          18 :   return Res;
    8269             : }
    8270             : 
    8271         683 : static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
    8272             :                                                          SelectionDAG &DAG) {
    8273             :   // Take advantage of vector comparisons producing 0 or -1 in each lane to
    8274             :   // optimize away operation when it's from a constant.
    8275             :   //
    8276             :   // The general transformation is:
    8277             :   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
    8278             :   //       AND(VECTOR_CMP(x,y), constant2)
    8279             :   //    constant2 = UNARYOP(constant)
    8280             : 
    8281             :   // Early exit if this isn't a vector operation, the operand of the
    8282             :   // unary operation isn't a bitwise AND, or if the sizes of the operations
    8283             :   // aren't the same.
    8284        1366 :   EVT VT = N->getValueType(0);
    8285        1338 :   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
    8286         725 :       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
    8287         692 :       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
    8288         681 :     return SDValue();
    8289             : 
    8290             :   // Now check that the other operand of the AND is a constant. We could
    8291             :   // make the transformation for non-constant splats as well, but it's unclear
    8292             :   // that would be a benefit as it would not eliminate any operations, just
    8293             :   // perform one more step in scalar code before moving to the vector unit.
    8294             :   if (BuildVectorSDNode *BV =
    8295           8 :           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
    8296             :     // Bail out if the vector isn't a constant.
    8297           2 :     if (!BV->isConstant())
    8298           0 :       return SDValue();
    8299             : 
    8300             :     // Everything checks out. Build up the new and improved node.
    8301           2 :     SDLoc DL(N);
    8302           4 :     EVT IntVT = BV->getValueType(0);
    8303             :     // Create a new constant of the appropriate type for the transformed
    8304             :     // DAG.
    8305           6 :     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
    8306             :     // The AND node needs bitcasts to/from an integer vector type around it.
    8307           2 :     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
    8308             :     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
    8309           6 :                                  N->getOperand(0)->getOperand(0), MaskConst);
    8310           2 :     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
    8311           2 :     return Res;
    8312             :   }
    8313             : 
    8314           0 :   return SDValue();
    8315             : }
    8316             : 
    8317         683 : static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
    8318             :                                      const AArch64Subtarget *Subtarget) {
    8319             :   // First try to optimize away the conversion when it's conditionally from
    8320             :   // a constant. Vectors only.
    8321         683 :   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
    8322           2 :     return Res;
    8323             : 
    8324        1362 :   EVT VT = N->getValueType(0);
    8325        1202 :   if (VT != MVT::f32 && VT != MVT::f64)
    8326         365 :     return SDValue();
    8327             : 
    8328             :   // Only optimize when the source and destination types have the same width.
    8329         632 :   if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
    8330         186 :     return SDValue();
    8331             : 
    8332             :   // If the result of an integer load is only used by an integer-to-float
    8333             :   // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
    8334             :   // This eliminates an "integer-to-vector-move" UOP and improves throughput.
    8335         260 :   SDValue N0 = N->getOperand(0);
    8336         229 :   if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
    8337             :       // Do not change the width of a volatile load.
    8338          33 :       !cast<LoadSDNode>(N0)->isVolatile()) {
    8339          33 :     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
    8340         132 :     SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
    8341          66 :                                LN0->getPointerInfo(), LN0->getAlignment(),
    8342          99 :                                LN0->getMemOperand()->getFlags());
    8343             : 
    8344             :     // Make sure successors of the original load stay after it by updating them
    8345             :     // to use the new Chain.
    8346          99 :     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
    8347             : 
    8348             :     unsigned Opcode =
    8349          33 :         (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
    8350          99 :     return DAG.getNode(Opcode, SDLoc(N), VT, Load);
    8351             :   }
    8352             : 
    8353          97 :   return SDValue();
    8354             : }
    8355             : 
    8356             : /// Fold a floating-point multiply by power of two into floating-point to
    8357             : /// fixed-point conversion.
    8358         415 : static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
    8359             :                                      TargetLowering::DAGCombinerInfo &DCI,
    8360             :                                      const AArch64Subtarget *Subtarget) {
    8361         415 :   if (!Subtarget->hasNEON())
    8362           0 :     return SDValue();
    8363             : 
    8364         830 :   SDValue Op = N->getOperand(0);
    8365        1645 :   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
    8366         188 :       Op.getOpcode() != ISD::FMUL)
    8367         394 :     return SDValue();
    8368             : 
    8369          42 :   SDValue ConstVec = Op->getOperand(1);
    8370          21 :   if (!isa<BuildVectorSDNode>(ConstVec))
    8371           6 :     return SDValue();
    8372             : 
    8373          15 :   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
    8374          15 :   uint32_t FloatBits = FloatTy.getSizeInBits();
    8375          15 :   if (FloatBits != 32 && FloatBits != 64)
    8376           0 :     return SDValue();
    8377             : 
    8378          15 :   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
    8379          15 :   uint32_t IntBits = IntTy.getSizeInBits();
    8380          15 :   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
    8381           1 :     return SDValue();
    8382             : 
    8383             :   // Avoid conversions where iN is larger than the float (e.g., float -> i64).
    8384          14 :   if (IntBits > FloatBits)
    8385           1 :     return SDValue();
    8386             : 
    8387          13 :   BitVector UndefElements;
    8388          13 :   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
    8389          13 :   int32_t Bits = IntBits == 64 ? 64 : 32;
    8390          13 :   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
    8391          13 :   if (C == -1 || C == 0 || C > Bits)
    8392           4 :     return SDValue();
    8393             : 
    8394           9 :   MVT ResTy;
    8395          18 :   unsigned NumLanes = Op.getValueType().getVectorNumElements();
    8396           9 :   switch (NumLanes) {
    8397           0 :   default:
    8398           0 :     return SDValue();
    8399           7 :   case 2:
    8400           7 :     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
    8401           7 :     break;
    8402           2 :   case 4:
    8403           2 :     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
    8404           2 :     break;
    8405             :   }
    8406             : 
    8407           9 :   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
    8408           0 :     return SDValue();
    8409             : 
    8410             :   assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
    8411             :          "Illegal vector type after legalization");
    8412             : 
    8413          18 :   SDLoc DL(N);
    8414          18 :   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
    8415           9 :   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
    8416             :                                       : Intrinsic::aarch64_neon_vcvtfp2fxu;
    8417             :   SDValue FixConv =
    8418             :       DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
    8419           9 :                   DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
    8420          36 :                   Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
    8421             :   // We can handle smaller integers by generating an extra trunc.
    8422           9 :   if (IntBits < FloatBits)
    8423           4 :     FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
    8424             : 
    8425           9 :   return FixConv;
    8426             : }
    8427             : 
    8428             : /// Fold a floating-point divide by power of two into fixed-point to
    8429             : /// floating-point conversion.
    8430         183 : static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
    8431             :                                   TargetLowering::DAGCombinerInfo &DCI,
    8432             :                                   const AArch64Subtarget *Subtarget) {
    8433         183 :   if (!Subtarget->hasNEON())
    8434           0 :     return SDValue();
    8435             : 
    8436         366 :   SDValue Op = N->getOperand(0);
    8437         366 :   unsigned Opc = Op->getOpcode();
    8438         971 :   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
    8439         499 :       !Op.getOperand(0).getValueType().isSimple() ||
    8440          79 :       (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
    8441         160 :     return SDValue();
    8442             : 
    8443          46 :   SDValue ConstVec = N->getOperand(1);
    8444          23 :   if (!isa<BuildVectorSDNode>(ConstVec))
    8445           2 :     return SDValue();
    8446             : 
    8447          63 :   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
    8448          21 :   int32_t IntBits = IntTy.getSizeInBits();
    8449          21 :   if (IntBits != 16 && IntBits != 32 && IntBits != 64)
    8450           0 :     return SDValue();
    8451             : 
    8452          21 :   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
    8453          21 :   int32_t FloatBits = FloatTy.getSizeInBits();
    8454          21 :   if (FloatBits != 32 && FloatBits != 64)
    8455           0 :     return SDValue();
    8456             : 
    8457             :   // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
    8458          21 :   if (IntBits > FloatBits)
    8459           1 :     return SDValue();
    8460             : 
    8461          20 :   BitVector UndefElements;
    8462          20 :   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
    8463          20 :   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
    8464          20 :   if (C == -1 || C == 0 || C > FloatBits)
    8465           2 :     return SDValue();
    8466             : 
    8467          18 :   MVT ResTy;
    8468          36 :   unsigned NumLanes = Op.getValueType().getVectorNumElements();
    8469          18 :   switch (NumLanes) {
    8470           0 :   default:
    8471           0 :     return SDValue();
    8472          14 :   case 2:
    8473          14 :     ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
    8474          14 :     break;
    8475           4 :   case 4:
    8476           4 :     ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
    8477           4 :     break;
    8478             :   }
    8479             : 
    8480          19 :   if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
    8481           1 :     return SDValue();
    8482             : 
    8483          34 :   SDLoc DL(N);
    8484          34 :   SDValue ConvInput = Op.getOperand(0);
    8485          17 :   bool IsSigned = Opc == ISD::SINT_TO_FP;
    8486          17 :   if (IntBits < FloatBits)
    8487          10 :     ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
    8488          30 :                             ResTy, ConvInput);
    8489             : 
    8490          17 :   unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
    8491             :                                       : Intrinsic::aarch64_neon_vcvtfxu2fp;
    8492             :   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
    8493          17 :                      DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
    8494          51 :                      DAG.getConstant(C, DL, MVT::i32));
    8495             : }
    8496             : 
    8497             : /// An EXTR instruction is made up of two shifts, ORed together. This helper
    8498             : /// searches for and classifies those shifts.
    8499         503 : static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
    8500             :                          bool &FromHi) {
    8501        1006 :   if (N.getOpcode() == ISD::SHL)
    8502          80 :     FromHi = false;
    8503         846 :   else if (N.getOpcode() == ISD::SRL)
    8504          19 :     FromHi = true;
    8505             :   else
    8506             :     return false;
    8507             : 
    8508         198 :   if (!isa<ConstantSDNode>(N.getOperand(1)))
    8509             :     return false;
    8510             : 
    8511         190 :   ShiftAmount = N->getConstantOperandVal(1);
    8512         190 :   Src = N->getOperand(0);
    8513             :   return true;
    8514             : }
    8515             : 
    8516             : /// EXTR instruction extracts a contiguous chunk of bits from two existing
    8517             : /// registers viewed as a high/low pair. This function looks for the pattern:
    8518             : /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
    8519             : /// with an EXTR. Can't quite be done in TableGen because the two immediates
    8520             : /// aren't independent.
    8521         835 : static SDValue tryCombineToEXTR(SDNode *N,
    8522             :                                 TargetLowering::DAGCombinerInfo &DCI) {
    8523         835 :   SelectionDAG &DAG = DCI.DAG;
    8524        1670 :   SDLoc DL(N);
    8525        1670 :   EVT VT = N->getValueType(0);
    8526             : 
    8527             :   assert(N->getOpcode() == ISD::OR && "Unexpected root");
    8528             : 
    8529        1443 :   if (VT != MVT::i32 && VT != MVT::i64)
    8530         398 :     return SDValue();
    8531             : 
    8532         437 :   SDValue LHS;
    8533         437 :   uint32_t ShiftLHS = 0;
    8534         437 :   bool LHSFromHi = false;
    8535         874 :   if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
    8536         371 :     return SDValue();
    8537             : 
    8538          66 :   SDValue RHS;
    8539          66 :   uint32_t ShiftRHS = 0;
    8540          66 :   bool RHSFromHi = false;
    8541         132 :   if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
    8542          37 :     return SDValue();
    8543             : 
    8544             :   // If they're both trying to come from the high part of the register, they're
    8545             :   // not really an EXTR.
    8546          29 :   if (LHSFromHi == RHSFromHi)
    8547          16 :     return SDValue();
    8548             : 
    8549          13 :   if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
    8550           4 :     return SDValue();
    8551             : 
    8552           9 :   if (LHSFromHi) {
    8553           3 :     std::swap(LHS, RHS);
    8554             :     std::swap(ShiftLHS, ShiftRHS);
    8555             :   }
    8556             : 
    8557             :   return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
    8558           9 :                      DAG.getConstant(ShiftRHS, DL, MVT::i64));
    8559             : }
    8560             : 
    8561         826 : static SDValue tryCombineToBSL(SDNode *N,
    8562             :                                 TargetLowering::DAGCombinerInfo &DCI) {
    8563        1652 :   EVT VT = N->getValueType(0);
    8564         826 :   SelectionDAG &DAG = DCI.DAG;
    8565        1652 :   SDLoc DL(N);
    8566             : 
    8567         826 :   if (!VT.isVector())
    8568         428 :     return SDValue();
    8569             : 
    8570         796 :   SDValue N0 = N->getOperand(0);
    8571         796 :   if (N0.getOpcode() != ISD::AND)
    8572         249 :     return SDValue();
    8573             : 
    8574         298 :   SDValue N1 = N->getOperand(1);
    8575         298 :   if (N1.getOpcode() != ISD::AND)
    8576          12 :     return SDValue();
    8577             : 
    8578             :   // We only have to look for constant vectors here since the general, variable
    8579             :   // case can be handled in TableGen.
    8580         137 :   unsigned Bits = VT.getScalarSizeInBits();
    8581         137 :   uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
    8582         395 :   for (int i = 1; i >= 0; --i)
    8583        1298 :     for (int j = 1; j >= 0; --j) {
    8584        1572 :       BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
    8585        1572 :       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
    8586         524 :       if (!BVN0 || !BVN1)
    8587             :         continue;
    8588             : 
    8589             :       bool FoundMatch = true;
    8590         101 :       for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
    8591         144 :         ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
    8592         144 :         ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
    8593          96 :         if (!CN0 || !CN1 ||
    8594          48 :             CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
    8595             :           FoundMatch = false;
    8596             :           break;
    8597             :         }
    8598             :       }
    8599             : 
    8600          11 :       if (FoundMatch)
    8601             :         return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
    8602          32 :                            N0->getOperand(1 - i), N1->getOperand(1 - j));
    8603             :     }
    8604             : 
    8605         129 :   return SDValue();
    8606             : }
    8607             : 
    8608         882 : static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
    8609             :                                 const AArch64Subtarget *Subtarget) {
    8610             :   // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
    8611         882 :   SelectionDAG &DAG = DCI.DAG;
    8612        1764 :   EVT VT = N->getValueType(0);
    8613             : 
    8614        1717 :   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
    8615          47 :     return SDValue();
    8616             : 
    8617         835 :   if (SDValue Res = tryCombineToEXTR(N, DCI))
    8618           9 :     return Res;
    8619             : 
    8620         826 :   if (SDValue Res = tryCombineToBSL(N, DCI))
    8621           8 :     return Res;
    8622             : 
    8623         818 :   return SDValue();
    8624             : }
    8625             : 
    8626         645 : static SDValue performSRLCombine(SDNode *N,
    8627             :                                  TargetLowering::DAGCombinerInfo &DCI) {
    8628         645 :   SelectionDAG &DAG = DCI.DAG;
    8629        1290 :   EVT VT = N->getValueType(0);
    8630        1096 :   if (VT != MVT::i32 && VT != MVT::i64)
    8631         170 :     return SDValue();
    8632             : 
    8633             :   // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
    8634             :   // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
    8635             :   // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
    8636         950 :   SDValue N0 = N->getOperand(0);
    8637         950 :   if (N0.getOpcode() == ISD::BSWAP) {
    8638           2 :     SDLoc DL(N);
    8639           4 :     SDValue N1 = N->getOperand(1);
    8640           4 :     SDValue N00 = N0.getOperand(0);
    8641           2 :     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
    8642           2 :       uint64_t ShiftAmt = C->getZExtValue();
    8643           8 :       if (VT == MVT::i32 && ShiftAmt == 16 &&
    8644           4 :           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
    8645           1 :         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
    8646           5 :       if (VT == MVT::i64 && ShiftAmt == 32 &&
    8647           2 :           DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
    8648           1 :         return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
    8649             :     }
    8650             :   }
    8651         473 :   return SDValue();
    8652             : }
    8653             : 
    8654        8998 : static SDValue performBitcastCombine(SDNode *N,
    8655             :                                      TargetLowering::DAGCombinerInfo &DCI,
    8656             :                                      SelectionDAG &DAG) {
    8657             :   // Wait 'til after everything is legalized to try this. That way we have
    8658             :   // legal vector types and such.
    8659       17996 :   if (DCI.isBeforeLegalizeOps())
    8660        4227 :     return SDValue();
    8661             : 
    8662             :   // Remove extraneous bitcasts around an extract_subvector.
    8663             :   // For example,
    8664             :   //    (v4i16 (bitconvert
    8665             :   //             (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
    8666             :   //  becomes
    8667             :   //    (extract_subvector ((v8i16 ...), (i64 4)))
    8668             : 
    8669             :   // Only interested in 64-bit vectors as the ultimate result.
    8670        9542 :   EVT VT = N->getValueType(0);
    8671        4771 :   if (!VT.isVector())
    8672         506 :     return SDValue();
    8673        4265 :   if (VT.getSimpleVT().getSizeInBits() != 64)
    8674        2800 :     return SDValue();
    8675             :   // Is the operand an extract_subvector starting at the beginning or halfway
    8676             :   // point of the vector? A low half may also come through as an
    8677             :   // EXTRACT_SUBREG, so look for that, too.
    8678        2930 :   SDValue Op0 = N->getOperand(0);
    8679        4333 :   if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
    8680        1438 :       !(Op0->isMachineOpcode() &&
    8681          35 :         Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
    8682        1368 :     return SDValue();
    8683         388 :   uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
    8684          97 :   if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
    8685         124 :     if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
    8686           0 :       return SDValue();
    8687          35 :   } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
    8688          35 :     if (idx != AArch64::dsub)
    8689           0 :       return SDValue();
    8690             :     // The dsub reference is equivalent to a lane zero subvector reference.
    8691             :     idx = 0;
    8692             :   }
    8693             :   // Look through the bitcast of the input to the extract.
    8694         194 :   if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
    8695          38 :     return SDValue();
    8696         177 :   SDValue Source = Op0->getOperand(0)->getOperand(0);
    8697             :   // If the source type has twice the number of elements as our destination
    8698             :   // type, we know this is an extract of the high or low half of the vector.
    8699         118 :   EVT SVT = Source->getValueType(0);
    8700          59 :   if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
    8701           7 :     return SDValue();
    8702             : 
    8703             :   DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
    8704             : 
    8705             :   // Create the simplified form to just extract the low or high half of the
    8706             :   // vector directly rather than bothering with the bitcasts.
    8707          52 :   SDLoc dl(N);
    8708          52 :   unsigned NumElements = VT.getVectorNumElements();
    8709          52 :   if (idx) {
    8710          52 :     SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
    8711          52 :     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
    8712             :   } else {
    8713           0 :     SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
    8714           0 :     return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
    8715             :                                       Source, SubReg),
    8716           0 :                    0);
    8717             :   }
    8718             : }
    8719             : 
    8720         722 : static SDValue performConcatVectorsCombine(SDNode *N,
    8721             :                                            TargetLowering::DAGCombinerInfo &DCI,
    8722             :                                            SelectionDAG &DAG) {
    8723        1444 :   SDLoc dl(N);
    8724        1444 :   EVT VT = N->getValueType(0);
    8725        2166 :   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
    8726             : 
    8727             :   // Optimize concat_vectors of truncated vectors, where the intermediate
    8728             :   // type is illegal, to avoid said illegality,  e.g.,
    8729             :   //   (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
    8730             :   //                          (v2i16 (truncate (v2i64)))))
    8731             :   // ->
    8732             :   //   (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
    8733             :   //                                    (v4i32 (bitcast (v2i64))),
    8734             :   //                                    <0, 2, 4, 6>)))
    8735             :   // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
    8736             :   // on both input and result type, so we might generate worse code.
    8737             :   // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
    8738        1416 :   if (N->getNumOperands() == 2 &&
    8739         756 :       N0->getOpcode() == ISD::TRUNCATE &&
    8740          34 :       N1->getOpcode() == ISD::TRUNCATE) {
    8741          66 :     SDValue N00 = N0->getOperand(0);
    8742          66 :     SDValue N10 = N1->getOperand(0);
    8743          66 :     EVT N00VT = N00.getValueType();
    8744             : 
    8745          66 :     if (N00VT == N10.getValueType() &&
    8746          84 :         (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
    8747          62 :         N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
    8748           4 :       MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
    8749           6 :       SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
    8750          28 :       for (size_t i = 0; i < Mask.size(); ++i)
    8751          24 :         Mask[i] = i * 2;
    8752             :       return DAG.getNode(ISD::TRUNCATE, dl, VT,
    8753             :                          DAG.getVectorShuffle(
    8754             :                              MidVT, dl,
    8755             :                              DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
    8756          14 :                              DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
    8757             :     }
    8758             :   }
    8759             : 
    8760             :   // Wait 'til after everything is legalized to try this. That way we have
    8761             :   // legal vector types and such.
    8762        1440 :   if (DCI.isBeforeLegalizeOps())
    8763         379 :     return SDValue();
    8764             : 
    8765             :   // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
    8766             :   // splat. The indexed instructions are going to be expecting a DUPLANE64, so
    8767             :   // canonicalise to that.
    8768          21 :   if (N0 == N1 && VT.getVectorNumElements() == 2) {
    8769             :     assert(VT.getScalarSizeInBits() == 64);
    8770             :     return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
    8771          18 :                        DAG.getConstant(0, dl, MVT::i64));
    8772             :   }
    8773             : 
    8774             :   // Canonicalise concat_vectors so that the right-hand vector has as few
    8775             :   // bit-casts as possible before its real operation. The primary matching
    8776             :   // destination for these operations will be the narrowing "2" instructions,
    8777             :   // which depend on the operation being performed on this right-hand vector.
    8778             :   // For example,
    8779             :   //    (concat_vectors LHS,  (v1i64 (bitconvert (v4i16 RHS))))
    8780             :   // becomes
    8781             :   //    (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
    8782             : 
    8783         332 :   if (N1->getOpcode() != ISD::BITCAST)
    8784         271 :     return SDValue();
    8785         122 :   SDValue RHS = N1->getOperand(0);
    8786         122 :   MVT RHSTy = RHS.getValueType().getSimpleVT();
    8787             :   // If the RHS is not a vector, this is not the pattern we're looking for.
    8788          61 :   if (!RHSTy.isVector())
    8789           0 :     return SDValue();
    8790             : 
    8791             :   DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
    8792             : 
    8793             :   MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
    8794          61 :                                   RHSTy.getVectorNumElements() * 2);
    8795             :   return DAG.getNode(ISD::BITCAST, dl, VT,
    8796             :                      DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
    8797             :                                  DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
    8798         305 :                                  RHS));
    8799             : }
    8800             : 
    8801          65 : static SDValue tryCombineFixedPointConvert(SDNode *N,
    8802             :                                            TargetLowering::DAGCombinerInfo &DCI,
    8803             :                                            SelectionDAG &DAG) {
    8804             :   // Wait 'til after everything is legalized to try this. That way we have
    8805             :   // legal vector types and such.
    8806         130 :   if (DCI.isBeforeLegalizeOps())
    8807          32 :     return SDValue();
    8808             :   // Transform a scalar conversion of a value from a lane extract into a
    8809             :   // lane extract of a vector conversion. E.g., from foo1 to foo2:
    8810             :   // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
    8811             :   // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
    8812             :   //
    8813             :   // The second form interacts better with instruction selection and the
    8814             :   // register allocator to avoid cross-class register copies that aren't
    8815             :   // coalescable due to a lane reference.
    8816             : 
    8817             :   // Check the operand and see if it originates from a lane extract.
    8818          66 :   SDValue Op1 = N->getOperand(1);
    8819          66 :   if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
    8820             :     // Yep, no additional predication needed. Perform the transform.
    8821           2 :     SDValue IID = N->getOperand(0);
    8822           2 :     SDValue Shift = N->getOperand(2);
    8823           2 :     SDValue Vec = Op1.getOperand(0);
    8824           2 :     SDValue Lane = Op1.getOperand(1);
    8825           2 :     EVT ResTy = N->getValueType(0);
    8826           1 :     EVT VecResTy;
    8827           2 :     SDLoc DL(N);
    8828             : 
    8829             :     // The vector width should be 128 bits by the time we get here, even
    8830             :     // if it started as 64 bits (the extract_vector handling will have
    8831             :     // done so).
    8832             :     assert(Vec.getValueSizeInBits() == 128 &&
    8833             :            "unexpected vector size on extract_vector_elt!");
    8834           3 :     if (Vec.getValueType() == MVT::v4i32)
    8835           0 :       VecResTy = MVT::v4f32;
    8836           3 :     else if (Vec.getValueType() == MVT::v2i64)
    8837           1 :       VecResTy = MVT::v2f64;
    8838             :     else
    8839           0 :       llvm_unreachable("unexpected vector type!");
    8840             : 
    8841             :     SDValue Convert =
    8842           1 :         DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
    8843           1 :     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
    8844             :   }
    8845          32 :   return SDValue();
    8846             : }
    8847             : 
    8848             : // AArch64 high-vector "long" operations are formed by performing the non-high
    8849             : // version on an extract_subvector of each operand which gets the high half:
    8850             : //
    8851             : //  (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
    8852             : //
    8853             : // However, there are cases which don't have an extract_high explicitly, but
    8854             : // have another operation that can be made compatible with one for free. For
    8855             : // example:
    8856             : //
    8857             : //  (dupv64 scalar) --> (extract_high (dup128 scalar))
    8858             : //
    8859             : // This routine does the actual conversion of such DUPs, once outer routines
    8860             : // have determined that everything else is in order.
    8861             : // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
    8862             : // similarly here.
    8863         516 : static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
    8864         516 :   switch (N.getOpcode()) {
    8865             :   case AArch64ISD::DUP:
    8866             :   case AArch64ISD::DUPLANE8:
    8867             :   case AArch64ISD::DUPLANE16:
    8868             :   case AArch64ISD::DUPLANE32:
    8869             :   case AArch64ISD::DUPLANE64:
    8870             :   case AArch64ISD::MOVI:
    8871             :   case AArch64ISD::MOVIshift:
    8872             :   case AArch64ISD::MOVIedit:
    8873             :   case AArch64ISD::MOVImsl:
    8874             :   case AArch64ISD::MVNIshift:
    8875             :   case AArch64ISD::MVNImsl:
    8876             :     break;
    8877         332 :   default:
    8878             :     // FMOV could be supported, but isn't very useful, as it would only occur
    8879             :     // if you passed a bitcast' floating point immediate to an eligible long
    8880             :     // integer op (addl, smull, ...).
    8881         332 :     return SDValue();
    8882             :   }
    8883             : 
    8884         184 :   MVT NarrowTy = N.getSimpleValueType();
    8885         184 :   if (!NarrowTy.is64BitVector())
    8886           0 :     return SDValue();
    8887             : 
    8888         184 :   MVT ElementTy = NarrowTy.getVectorElementType();
    8889         184 :   unsigned NumElems = NarrowTy.getVectorNumElements();
    8890         184 :   MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
    8891             : 
    8892         184 :   SDLoc dl(N);
    8893             :   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
    8894             :                      DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
    8895        1104 :                      DAG.getConstant(NumElems, dl, MVT::i64));
    8896             : }
    8897             : 
    8898             : static bool isEssentiallyExtractSubvector(SDValue N) {
    8899        2216 :   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
    8900             :     return true;
    8901             : 
    8902        1348 :   return N.getOpcode() == ISD::BITCAST &&
    8903         112 :          N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
    8904             : }
    8905             : 
    8906             : /// \brief Helper structure to keep track of ISD::SET_CC operands.
    8907             : struct GenericSetCCInfo {
    8908             :   const SDValue *Opnd0;
    8909             :   const SDValue *Opnd1;
    8910             :   ISD::CondCode CC;
    8911             : };
    8912             : 
    8913             : /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
    8914             : struct AArch64SetCCInfo {
    8915             :   const SDValue *Cmp;
    8916             :   AArch64CC::CondCode CC;
    8917             : };
    8918             : 
    8919             : /// \brief Helper structure to keep track of SetCC information.
    8920             : union SetCCInfo {
    8921             :   GenericSetCCInfo Generic;
    8922             :   AArch64SetCCInfo AArch64;
    8923             : };
    8924             : 
    8925             : /// \brief Helper structure to be able to read SetCC information.  If set to
    8926             : /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
    8927             : /// GenericSetCCInfo.
    8928             : struct SetCCInfoAndKind {
    8929             :   SetCCInfo Info;
    8930             :   bool IsAArch64;
    8931             : };
    8932             : 
    8933             : /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
    8934             : /// an
    8935             : /// AArch64 lowered one.
    8936             : /// \p SetCCInfo is filled accordingly.
    8937             : /// \post SetCCInfo is meanginfull only when this function returns true.
    8938             : /// \return True when Op is a kind of SET_CC operation.
    8939        9557 : static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
    8940             :   // If this is a setcc, this is straight forward.
    8941       19114 :   if (Op.getOpcode() == ISD::SETCC) {
    8942           0 :     SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
    8943           0 :     SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
    8944           0 :     SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
    8945           0 :     SetCCInfo.IsAArch64 = false;
    8946             :     return true;
    8947             :   }
    8948             :   // Otherwise, check if this is a matching csel instruction.
    8949             :   // In other words:
    8950             :   // - csel 1, 0, cc
    8951             :   // - csel 0, 1, !cc
    8952       19114 :   if (Op.getOpcode() != AArch64ISD::CSEL)
    8953             :     return false;
    8954             :   // Set the information about the operands.
    8955             :   // TODO: we want the operands of the Cmp not the csel
    8956          18 :   SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
    8957           9 :   SetCCInfo.IsAArch64 = true;
    8958           9 :   SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
    8959          27 :       cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
    8960             : 
    8961             :   // Check that the operands matches the constraints:
    8962             :   // (1) Both operands must be constants.
    8963             :   // (2) One must be 1 and the other must be 0.
    8964          27 :   ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
    8965          27 :   ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
    8966             : 
    8967             :   // Check (1).
    8968           9 :   if (!TValue || !FValue)
    8969             :     return false;
    8970             : 
    8971             :   // Check (2).
    8972           8 :   if (!TValue->isOne()) {
    8973             :     // Update the comparison when we are interested in !cc.
    8974           4 :     std::swap(TValue, FValue);
    8975           4 :     SetCCInfo.Info.AArch64.CC =
    8976           8 :         AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
    8977             :   }
    8978          12 :   return TValue->isOne() && FValue->isNullValue();
    8979             : }
    8980             : 
    8981             : // Returns true if Op is setcc or zext of setcc.
    8982        9522 : static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
    8983        9522 :   if (isSetCC(Op, Info))
    8984             :     return true;
    8985       19075 :   return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
    8986          70 :     isSetCC(Op->getOperand(0), Info));
    8987             : }
    8988             : 
    8989             : // The folding we want to perform is:
    8990             : // (add x, [zext] (setcc cc ...) )
    8991             : //   -->
    8992             : // (csel x, (add x, 1), !cc ...)
    8993             : //
    8994             : // The latter will get matched to a CSINC instruction.
    8995        4762 : static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
    8996             :   assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
    8997        9524 :   SDValue LHS = Op->getOperand(0);
    8998        9524 :   SDValue RHS = Op->getOperand(1);
    8999             :   SetCCInfoAndKind InfoAndKind;
    9000             : 
    9001             :   // If neither operand is a SET_CC, give up.
    9002        4762 :   if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
    9003        4760 :     std::swap(LHS, RHS);
    9004        4760 :     if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
    9005        4758 :       return SDValue();
    9006             :   }
    9007             : 
    9008             :   // FIXME: This could be generatized to work for FP comparisons.
    9009           4 :   EVT CmpVT = InfoAndKind.IsAArch64
    9010           8 :                   ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
    9011           8 :                   : InfoAndKind.Info.Generic.Opnd0->getValueType();
    9012           6 :   if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
    9013           0 :     return SDValue();
    9014             : 
    9015           4 :   SDValue CCVal;
    9016           4 :   SDValue Cmp;
    9017           4 :   SDLoc dl(Op);
    9018           4 :   if (InfoAndKind.IsAArch64) {
    9019           4 :     CCVal = DAG.getConstant(
    9020           8 :         AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
    9021          12 :         MVT::i32);
    9022           4 :     Cmp = *InfoAndKind.Info.AArch64.Cmp;
    9023             :   } else
    9024           0 :     Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
    9025           0 :                       *InfoAndKind.Info.Generic.Opnd1,
    9026             :                       ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
    9027           0 :                       CCVal, DAG, dl);
    9028             : 
    9029           8 :   EVT VT = Op->getValueType(0);
    9030           4 :   LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
    9031           4 :   return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
    9032             : }
    9033             : 
    9034             : // The basic add/sub long vector instructions have variants with "2" on the end
    9035             : // which act on the high-half of their inputs. They are normally matched by
    9036             : // patterns like:
    9037             : //
    9038             : // (add (zeroext (extract_high LHS)),
    9039             : //      (zeroext (extract_high RHS)))
    9040             : // -> uaddl2 vD, vN, vM
    9041             : //
    9042             : // However, if one of the extracts is something like a duplicate, this
    9043             : // instruction can still be used profitably. This function puts the DAG into a
    9044             : // more appropriate form for those patterns to trigger.
    9045       13286 : static SDValue performAddSubLongCombine(SDNode *N,
    9046             :                                         TargetLowering::DAGCombinerInfo &DCI,
    9047             :                                         SelectionDAG &DAG) {
    9048       26572 :   if (DCI.isBeforeLegalizeOps())
    9049        7025 :     return SDValue();
    9050             : 
    9051        6261 :   MVT VT = N->getSimpleValueType(0);
    9052        6261 :   if (!VT.is128BitVector()) {
    9053        5193 :     if (N->getOpcode() == ISD::ADD)
    9054        4762 :       return performSetccAddFolding(N, DAG);
    9055         431 :     return SDValue();
    9056             :   }
    9057             : 
    9058             :   // Make sure both branches are extended in the same way.
    9059        2136 :   SDValue LHS = N->getOperand(0);
    9060        2136 :   SDValue RHS = N->getOperand(1);
    9061        2058 :   if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
    9062        1199 :        LHS.getOpcode() != ISD::SIGN_EXTEND) ||
    9063         262 :       LHS.getOpcode() != RHS.getOpcode())
    9064         963 :     return SDValue();
    9065             : 
    9066         210 :   unsigned ExtType = LHS.getOpcode();
    9067             : 
    9068             :   // It's not worth doing if at least one of the inputs isn't already an
    9069             :   // extract, but we don't know which it'll be so we have to try both.
    9070         210 :   if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
    9071         116 :     RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
    9072          58 :     if (!RHS.getNode())
    9073          56 :       return SDValue();
    9074             : 
    9075           8 :     RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
    9076          94 :   } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
    9077           4 :     LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
    9078           2 :     if (!LHS.getNode())
    9079           0 :       return SDValue();
    9080             : 
    9081           8 :     LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
    9082             :   }
    9083             : 
    9084         245 :   return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
    9085             : }
    9086             : 
    9087             : // Massage DAGs which we can use the high-half "long" operations on into
    9088             : // something isel will recognize better. E.g.
    9089             : //
    9090             : // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
    9091             : //   (aarch64_neon_umull (extract_high (v2i64 vec)))
    9092             : //                     (extract_high (v2i64 (dup128 scalar)))))
    9093             : //
    9094        1210 : static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
    9095             :                                        TargetLowering::DAGCombinerInfo &DCI,
    9096             :                                        SelectionDAG &DAG) {
    9097        2420 :   if (DCI.isBeforeLegalizeOps())
    9098         504 :     return SDValue();
    9099             : 
    9100        1412 :   SDValue LHS = N->getOperand(1);
    9101        1412 :   SDValue RHS = N->getOperand(2);
    9102             :   assert(LHS.getValueType().is64BitVector() &&
    9103             :          RHS.getValueType().is64BitVector() &&
    9104             :          "unexpected shape for long operation");
    9105             : 
    9106             :   // Either node could be a DUP, but it's not worth doing both of them (you'd
    9107             :   // just as well use the non-high version) so look for a corresponding extract
    9108             :   // operation on the other "wing".
    9109         706 :   if (isEssentiallyExtractSubvector(LHS)) {
    9110         456 :     RHS = tryExtendDUPToExtractHigh(RHS, DAG);
    9111         456 :     if (!RHS.getNode())
    9112         276 :       return SDValue();
    9113         250 :   } else if (isEssentiallyExtractSubvector(RHS)) {
    9114           0 :     LHS = tryExtendDUPToExtractHigh(LHS, DAG);
    9115           0 :     if (!LHS.getNode())
    9116           0 :       return SDValue();
    9117             :   }
    9118             : 
    9119         860 :   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
    9120        1720 :                      N->getOperand(0), LHS, RHS);
    9121             : }
    9122             : 
    9123         110 : static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
    9124         220 :   MVT ElemTy = N->getSimpleValueType(0).getScalarType();
    9125         110 :   unsigned ElemBits = ElemTy.getSizeInBits();
    9126             : 
    9127             :   int64_t ShiftAmount;
    9128         271 :   if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
    9129         204 :     APInt SplatValue, SplatUndef;
    9130             :     unsigned SplatBitSize;
    9131             :     bool HasAnyUndefs;
    9132          51 :     if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
    9133         102 :                               HasAnyUndefs, ElemBits) ||
    9134          51 :         SplatBitSize != ElemBits)
    9135           0 :       return SDValue();
    9136             : 
    9137          51 :     ShiftAmount = SplatValue.getSExtValue();
    9138         120 :   } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
    9139             :     ShiftAmount = CVN->getSExtValue();
    9140             :   } else
    9141          57 :     return SDValue();
    9142             : 
    9143             :   unsigned Opcode;
    9144             :   bool IsRightShift;
    9145          53 :   switch (IID) {
    9146           0 :   default:
    9147           0 :     llvm_unreachable("Unknown shift intrinsic");
    9148             :   case Intrinsic::aarch64_neon_sqshl:
    9149             :     Opcode = AArch64ISD::SQSHL_I;
    9150             :     IsRightShift = false;
    9151             :     break;
    9152          10 :   case Intrinsic::aarch64_neon_uqshl:
    9153          10 :     Opcode = AArch64ISD::UQSHL_I;
    9154          10 :     IsRightShift = false;
    9155          10 :     break;
    9156          14 :   case Intrinsic::aarch64_neon_srshl:
    9157          14 :     Opcode = AArch64ISD::SRSHR_I;
    9158          14 :     IsRightShift = true;
    9159          14 :     break;
    9160          14 :   case Intrinsic::aarch64_neon_urshl:
    9161          14 :     Opcode = AArch64ISD::URSHR_I;
    9162          14 :     IsRightShift = true;
    9163          14 :     break;
    9164           7 :   case Intrinsic::aarch64_neon_sqshlu:
    9165           7 :     Opcode = AArch64ISD::SQSHLU_I;
    9166           7 :     IsRightShift = false;
    9167           7 :     break;
    9168             :   }
    9169             : 
    9170          53 :   if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
    9171          56 :     SDLoc dl(N);
    9172          56 :     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
    9173         112 :                        DAG.getConstant(-ShiftAmount, dl, MVT::i32));
    9174          25 :   } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
    9175          46 :     SDLoc dl(N);
    9176          46 :     return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
    9177          92 :                        DAG.getConstant(ShiftAmount, dl, MVT::i32));
    9178             :   }
    9179             : 
    9180           2 :   return SDValue();
    9181             : }
    9182             : 
    9183             : // The CRC32[BH] instructions ignore the high bits of their data operand. Since
    9184             : // the intrinsics must be legal and take an i32, this means there's almost
    9185             : // certainly going to be a zext in the DAG which we can eliminate.
    9186          32 : static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
    9187          64 :   SDValue AndN = N->getOperand(2);
    9188          64 :   if (AndN.getOpcode() != ISD::AND)
    9189          24 :     return SDValue();
    9190             : 
    9191          24 :   ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
    9192           8 :   if (!CMask || CMask->getZExtValue() != Mask)
    9193           0 :     return SDValue();
    9194             : 
    9195          16 :   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
    9196          56 :                      N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
    9197             : }
    9198             : 
    9199         114 : static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
    9200             :                                            SelectionDAG &DAG) {
    9201         228 :   SDLoc dl(N);
    9202             :   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
    9203             :                      DAG.getNode(Opc, dl,
    9204         228 :                                  N->getOperand(1).getSimpleValueType(),
    9205         228 :                                  N->getOperand(1)),
    9206         798 :                      DAG.getConstant(0, dl, MVT::i64));
    9207             : }
    9208             : 
    9209        5281 : static SDValue performIntrinsicCombine(SDNode *N,
    9210             :                                        TargetLowering::DAGCombinerInfo &DCI,
    9211             :                                        const AArch64Subtarget *Subtarget) {
    9212        5281 :   SelectionDAG &DAG = DCI.DAG;
    9213        5281 :   unsigned IID = getIntrinsicID(N);
    9214        5281 :   switch (IID) {
    9215             :   default:
    9216             :     break;
    9217          65 :   case Intrinsic::aarch64_neon_vcvtfxs2fp:
    9218             :   case Intrinsic::aarch64_neon_vcvtfxu2fp:
    9219          65 :     return tryCombineFixedPointConvert(N, DCI, DAG);
    9220          25 :   case Intrinsic::aarch64_neon_saddv:
    9221          25 :     return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
    9222          17 :   case Intrinsic::aarch64_neon_uaddv:
    9223          17 :     return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
    9224          17 :   case Intrinsic::aarch64_neon_sminv:
    9225          17 :     return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
    9226          19 :   case Intrinsic::aarch64_neon_uminv:
    9227          19 :     return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
    9228          17 :   case Intrinsic::aarch64_neon_smaxv:
    9229          17 :     return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
    9230          19 :   case Intrinsic::aarch64_neon_umaxv:
    9231          19 :     return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
    9232          10 :   case Intrinsic::aarch64_neon_fmax:
    9233          20 :     return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
    9234          60 :                        N->getOperand(1), N->getOperand(2));
    9235          10 :   case Intrinsic::aarch64_neon_fmin:
    9236          20 :     return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
    9237          60 :                        N->getOperand(1), N->getOperand(2));
    9238           5 :   case Intrinsic::aarch64_neon_fmaxnm:
    9239          10 :     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
    9240          30 :                        N->getOperand(1), N->getOperand(2));
    9241           5 :   case Intrinsic::aarch64_neon_fminnm:
    9242          10 :     return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
    9243          30 :                        N->getOperand(1), N->getOperand(2));
    9244        1158 :   case Intrinsic::aarch64_neon_smull:
    9245             :   case Intrinsic::aarch64_neon_umull:
    9246             :   case Intrinsic::aarch64_neon_pmull:
    9247             :   case Intrinsic::aarch64_neon_sqdmull:
    9248        1158 :     return tryCombineLongOpWithDup(IID, N, DCI, DAG);
    9249         110 :   case Intrinsic::aarch64_neon_sqshl:
    9250             :   case Intrinsic::aarch64_neon_uqshl:
    9251             :   case Intrinsic::aarch64_neon_sqshlu:
    9252             :   case Intrinsic::aarch64_neon_srshl:
    9253             :   case Intrinsic::aarch64_neon_urshl:
    9254         110 :     return tryCombineShiftImm(IID, N, DAG);
    9255          16 :   case Intrinsic::aarch64_crc32b:
    9256             :   case Intrinsic::aarch64_crc32cb:
    9257          16 :     return tryCombineCRC32(0xff, N, DAG);
    9258          16 :   case Intrinsic::aarch64_crc32h:
    9259             :   case Intrinsic::aarch64_crc32ch:
    9260          16 :     return tryCombineCRC32(0xffff, N, DAG);
    9261             :   }
    9262        3772 :   return SDValue();
    9263             : }
    9264             : 
    9265        2946 : static SDValue performExtendCombine(SDNode *N,
    9266             :                                     TargetLowering::DAGCombinerInfo &DCI,
    9267             :                                     SelectionDAG &DAG) {
    9268             :   // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
    9269             :   // we can convert that DUP into another extract_high (of a bigger DUP), which
    9270             :   // helps the backend to decide that an sabdl2 would be useful, saving a real
    9271             :   // extract_high operation.
    9272        6441 :   if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
    9273        1098 :       N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
    9274         112 :     SDNode *ABDNode = N->getOperand(0).getNode();
    9275          56 :     unsigned IID = getIntrinsicID(ABDNode);
    9276         112 :     if (IID == Intrinsic::aarch64_neon_sabd ||
    9277          56 :         IID == Intrinsic::aarch64_neon_uabd) {
    9278          52 :       SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
    9279          52 :       if (!NewABD.getNode())
    9280          14 :         return SDValue();
    9281             : 
    9282          76 :       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
    9283         152 :                          NewABD);
    9284             :     }
    9285             :   }
    9286             : 
    9287             :   // This is effectively a custom type legalization for AArch64.
    9288             :   //
    9289             :   // Type legalization will split an extend of a small, legal, type to a larger
    9290             :   // illegal type by first splitting the destination type, often creating
    9291             :   // illegal source types, which then get legalized in isel-confusing ways,
    9292             :   // leading to really terrible codegen. E.g.,
    9293             :   //   %result = v8i32 sext v8i8 %value
    9294             :   // becomes
    9295             :   //   %losrc = extract_subreg %value, ...
    9296             :   //   %hisrc = extract_subreg %value, ...
    9297             :   //   %lo = v4i32 sext v4i8 %losrc
    9298             :   //   %hi = v4i32 sext v4i8 %hisrc
    9299             :   // Things go rapidly downhill from there.
    9300             :   //
    9301             :   // For AArch64, the [sz]ext vector instructions can only go up one element
    9302             :   // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
    9303             :   // take two instructions.
    9304             :   //
    9305             :   // This implies that the most efficient way to do the extend from v8i8
    9306             :   // to two v4i32 values is to first extend the v8i8 to v8i16, then do
    9307             :   // the normal splitting to happen for the v8i16->v8i32.
    9308             : 
    9309             :   // This is pre-legalization to catch some cases where the default
    9310             :   // type legalization will create ill-tempered code.
    9311        2894 :   if (!DCI.isBeforeLegalizeOps())
    9312         976 :     return SDValue();
    9313             : 
    9314             :   // We're only interested in cleaning things up for non-legal vector types
    9315             :   // here. If both the source and destination are legal, things will just
    9316             :   // work naturally without any fiddling.
    9317        1918 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    9318        3836 :   EVT ResVT = N->getValueType(0);
    9319        1918 :   if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
    9320        1860 :     return SDValue();
    9321             :   // If the vector type isn't a simple VT, it's beyond the scope of what
    9322             :   // we're  worried about here. Let legalization do its thing and hope for
    9323             :   // the best.
    9324         116 :   SDValue Src = N->getOperand(0);
    9325         116 :   EVT SrcVT = Src->getValueType(0);
    9326         115 :   if (!ResVT.isSimple() || !SrcVT.isSimple())
    9327           1 :     return SDValue();
    9328             : 
    9329             :   // If the source VT is a 64-bit vector, we can play games and get the
    9330             :   // better results we want.
    9331          57 :   if (SrcVT.getSizeInBits() != 64)
    9332          50 :     return SDValue();
    9333             : 
    9334           7 :   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
    9335           7 :   unsigned ElementCount = SrcVT.getVectorNumElements();
    9336           7 :   SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
    9337           7 :   SDLoc DL(N);
    9338          14 :   Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
    9339             : 
    9340             :   // Now split the rest of the operation into two halves, each with a 64
    9341             :   // bit source.
    9342           7 :   EVT LoVT, HiVT;
    9343             :   SDValue Lo, Hi;
    9344           7 :   unsigned NumElements = ResVT.getVectorNumElements();
    9345             :   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
    9346           7 :   LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
    9347           7 :                                  ResVT.getVectorElementType(), NumElements / 2);
    9348             : 
    9349           7 :   EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
    9350          14 :                                LoVT.getVectorNumElements());
    9351           7 :   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
    9352          21 :                    DAG.getConstant(0, DL, MVT::i64));
    9353           7 :   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
    9354          21 :                    DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
    9355          14 :   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
    9356          14 :   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
    9357             : 
    9358             :   // Now combine the parts back together so we still have a single result
    9359             :   // like the combiner expects.
    9360           7 :   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
    9361             : }
    9362             : 
    9363          36 : static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
    9364             :                                SDValue SplatVal, unsigned NumVecElts) {
    9365          72 :   unsigned OrigAlignment = St.getAlignment();
    9366          72 :   unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
    9367             : 
    9368             :   // Create scalar stores. This is at least as good as the code sequence for a
    9369             :   // split unaligned store which is a dup.s, ext.b, and two stores.
    9370             :   // Most of the time the three stores should be replaced by store pair
    9371             :   // instructions (stp).
    9372         108 :   SDLoc DL(&St);
    9373          36 :   SDValue BasePtr = St.getBasePtr();
    9374          36 :   uint64_t BaseOffset = 0;
    9375             : 
    9376          72 :   const MachinePointerInfo &PtrInfo = St.getPointerInfo();
    9377             :   SDValue NewST1 =
    9378          72 :       DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
    9379          72 :                    OrigAlignment, St.getMemOperand()->getFlags());
    9380             : 
    9381             :   // As this in ISel, we will not merge this add which may degrade results.
    9382          36 :   if (BasePtr->getOpcode() == ISD::ADD &&
    9383          10 :       isa<ConstantSDNode>(BasePtr->getOperand(1))) {
    9384          20 :     BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
    9385          10 :     BasePtr = BasePtr->getOperand(0);
    9386             :   }
    9387             : 
    9388          36 :   unsigned Offset = EltOffset;
    9389         152 :   while (--NumVecElts) {
    9390         116 :     unsigned Alignment = MinAlign(OrigAlignment, Offset);
    9391             :     SDValue OffsetPtr =
    9392             :         DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
    9393         174 :                     DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
    9394          58 :     NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
    9395             :                           PtrInfo.getWithOffset(Offset), Alignment,
    9396         232 :                           St.getMemOperand()->getFlags());
    9397          58 :     Offset += EltOffset;
    9398             :   }
    9399          72 :   return NewST1;
    9400             : }
    9401             : 
    9402             : /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR.  The
    9403             : /// load store optimizer pass will merge them to store pair stores.  This should
    9404             : /// be better than a movi to create the vector zero followed by a vector store
    9405             : /// if the zero constant is not re-used, since one instructions and one register
    9406             : /// live range will be removed.
    9407             : ///
    9408             : /// For example, the final generated code should be:
    9409             : ///
    9410             : ///   stp xzr, xzr, [x0]
    9411             : ///
    9412             : /// instead of:
    9413             : ///
    9414             : ///   movi v0.2d, #0
    9415             : ///   str q0, [x0]
    9416             : ///
    9417        1111 : static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
    9418        1111 :   SDValue StVal = St.getValue();
    9419        2222 :   EVT VT = StVal.getValueType();
    9420             : 
    9421             :   // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
    9422             :   // 2, 3 or 4 i32 elements.
    9423        1111 :   int NumVecElts = VT.getVectorNumElements();
    9424        1425 :   if (!(((NumVecElts == 2 || NumVecElts == 3) &&
    9425        1425 :          VT.getVectorElementType().getSizeInBits() == 64) ||
    9426         390 :         ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
    9427        1501 :          VT.getVectorElementType().getSizeInBits() == 32)))
    9428         634 :     return SDValue();
    9429             : 
    9430         954 :   if (StVal.getOpcode() != ISD::BUILD_VECTOR)
    9431         379 :     return SDValue();
    9432             : 
    9433             :   // If the zero constant has more than one use then the vector store could be
    9434             :   // better since the constant mov will be amortized and stp q instructions
    9435             :   // should be able to be formed.
    9436         196 :   if (!StVal.hasOneUse())
    9437          55 :     return SDValue();
    9438             : 
    9439             :   // If the immediate offset of the address operand is too large for the stp
    9440             :   // instruction, then bail out.
    9441          43 :   if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
    9442          12 :     int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
    9443           6 :     if (Offset < -512 || Offset > 504)
    9444           1 :       return SDValue();
    9445             :   }
    9446             : 
    9447         222 :   for (int I = 0; I < NumVecElts; ++I) {
    9448         194 :     SDValue EltVal = StVal.getOperand(I);
    9449          97 :     if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
    9450           7 :       return SDValue();
    9451             :   }
    9452             : 
    9453             :   // Use WZR/XZR here to prevent DAGCombiner::MergeConsecutiveStores from
    9454             :   // undoing this transformation.
    9455          70 :   SDValue SplatVal = VT.getVectorElementType().getSizeInBits() == 32
    9456          48 :                          ? DAG.getRegister(AArch64::WZR, MVT::i32)
    9457          70 :                          : DAG.getRegister(AArch64::XZR, MVT::i64);
    9458          35 :   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
    9459             : }
    9460             : 
    9461             : /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
    9462             : /// value. The load store optimizer pass will merge them to store pair stores.
    9463             : /// This has better performance than a splat of the scalar followed by a split
    9464             : /// vector store. Even if the stores are not merged it is four stores vs a dup,
    9465             : /// followed by an ext.b and two stores.
    9466           6 : static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
    9467           6 :   SDValue StVal = St.getValue();
    9468          12 :   EVT VT = StVal.getValueType();
    9469             : 
    9470             :   // Don't replace floating point stores, they possibly won't be transformed to
    9471             :   // stp because of the store pair suppress pass.
    9472           6 :   if (VT.isFloatingPoint())
    9473           2 :     return SDValue();
    9474             : 
    9475             :   // We can express a splat as store pair(s) for 2 or 4 elements.
    9476           4 :   unsigned NumVecElts = VT.getVectorNumElements();
    9477           4 :   if (NumVecElts != 4 && NumVecElts != 2)
    9478           0 :     return SDValue();
    9479             : 
    9480             :   // Check that this is a splat.
    9481             :   // Make sure that each of the relevant vector element locations are inserted
    9482             :   // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
    9483           8 :   std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
    9484           4 :   SDValue SplatVal;
    9485          14 :   for (unsigned I = 0; I < NumVecElts; ++I) {
    9486             :     // Check for insert vector elements.
    9487          26 :     if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
    9488           2 :       return SDValue();
    9489             : 
    9490             :     // Check that same value is inserted at each vector element.
    9491          11 :     if (I == 0)
    9492           6 :       SplatVal = StVal.getOperand(1);
    9493          16 :     else if (StVal.getOperand(1) != SplatVal)
    9494           0 :       return SDValue();
    9495             : 
    9496             :     // Check insert element index.
    9497          32 :     ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
    9498             :     if (!CIndex)
    9499           1 :       return SDValue();
    9500          10 :     uint64_t IndexVal = CIndex->getZExtValue();
    9501          10 :     if (IndexVal >= NumVecElts)
    9502           0 :       return SDValue();
    9503          10 :     IndexNotInserted.reset(IndexVal);
    9504             : 
    9505          20 :     StVal = StVal.getOperand(0);
    9506             :   }
    9507             :   // Check that all vector element locations were inserted to.
    9508           1 :   if (IndexNotInserted.any())
    9509           0 :       return SDValue();
    9510             : 
    9511           1 :   return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
    9512             : }
    9513             : 
    9514       12194 : static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
    9515             :                            SelectionDAG &DAG,
    9516             :                            const AArch64Subtarget *Subtarget) {
    9517       12194 :   if (!DCI.isBeforeLegalize())
    9518        5771 :     return SDValue();
    9519             : 
    9520        6423 :   StoreSDNode *S = cast<StoreSDNode>(N);
    9521       18075 :   if (S->isVolatile() || S->isIndexed())
    9522        1194 :     return SDValue();
    9523             : 
    9524        5229 :   SDValue StVal = S->getValue();
    9525       10458 :   EVT VT = StVal.getValueType();
    9526        5229 :   if (!VT.isVector())
    9527        4118 :     return SDValue();
    9528             : 
    9529             :   // If we get a splat of zeros, convert this vector store to a store of
    9530             :   // scalars. They will be merged into store pairs of xzr thereby removing one
    9531             :   // instruction and one register.
    9532        1111 :   if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
    9533          35 :     return ReplacedZeroSplat;
    9534             : 
    9535             :   // FIXME: The logic for deciding if an unaligned store should be split should
    9536             :   // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
    9537             :   // a call to that function here.
    9538             : 
    9539        1076 :   if (!Subtarget->isMisaligned128StoreSlow())
    9540         957 :     return SDValue();
    9541             : 
    9542             :   // Don't split at -Oz.
    9543         238 :   if (DAG.getMachineFunction().getFunction()->optForMinSize())
    9544           0 :     return SDValue();
    9545             : 
    9546             :   // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
    9547             :   // those up regresses performance on micro-benchmarks and olden/bh.
    9548         233 :   if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
    9549           5 :     return SDValue();
    9550             : 
    9551             :   // Split unaligned 16B stores. They are terrible for performance.
    9552             :   // Don't split stores with alignment of 1 or 2. Code that uses clang vector
    9553             :   // extensions can use this to mark that it does not want splitting to happen
    9554             :   // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
    9555             :   // eliminating alignment hazards is only 1 in 8 for alignment of 2.
    9556         318 :   if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
    9557           8 :       S->getAlignment() <= 2)
    9558         108 :     return SDValue();
    9559             : 
    9560             :   // If we get a splat of a scalar convert this vector store to a store of
    9561             :   // scalars. They will be merged into store pairs thereby removing two
    9562             :   // instructions.
    9563           6 :   if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
    9564           1 :     return ReplacedSplat;
    9565             : 
    9566           5 :   SDLoc DL(S);
    9567           5 :   unsigned NumElts = VT.getVectorNumElements() / 2;
    9568             :   // Split VT into two.
    9569             :   EVT HalfVT =
    9570           5 :       EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
    9571             :   SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
    9572          10 :                                    DAG.getConstant(0, DL, MVT::i64));
    9573             :   SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
    9574          10 :                                    DAG.getConstant(NumElts, DL, MVT::i64));
    9575           5 :   SDValue BasePtr = S->getBasePtr();
    9576             :   SDValue NewST1 =
    9577          15 :       DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
    9578          10 :                    S->getAlignment(), S->getMemOperand()->getFlags());
    9579             :   SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
    9580          15 :                                   DAG.getConstant(8, DL, MVT::i64));
    9581             :   return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
    9582           5 :                       S->getPointerInfo(), S->getAlignment(),
    9583          15 :                       S->getMemOperand()->getFlags());
    9584             : }
    9585             : 
    9586             : /// Target-specific DAG combine function for post-increment LD1 (lane) and
    9587             : /// post-increment LD1R.
    9588        1630 : static SDValue performPostLD1Combine(SDNode *N,
    9589             :                                      TargetLowering::DAGCombinerInfo &DCI,
    9590             :                                      bool IsLaneOp) {
    9591        3260 :   if (DCI.isBeforeLegalizeOps())
    9592         676 :     return SDValue();
    9593             : 
    9594         954 :   SelectionDAG &DAG = DCI.DAG;
    9595        1908 :   EVT VT = N->getValueType(0);
    9596             : 
    9597         954 :   unsigned LoadIdx = IsLaneOp ? 1 : 0;
    9598        1908 :   SDNode *LD = N->getOperand(LoadIdx).getNode();
    9599             :   // If it is not LOAD, can not do such combine.
    9600         954 :   if (LD->getOpcode() != ISD::LOAD)
    9601         840 :     return SDValue();
    9602             : 
    9603         114 :   LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
    9604         114 :   EVT MemVT = LoadSDN->getMemoryVT();
    9605             :   // Check if memory operand is the same type as the vector element.
    9606         114 :   if (MemVT != VT.getVectorElementType())
    9607           6 :     return SDValue();
    9608             : 
    9609             :   // Check if there are other uses. If so, do not combine as it will introduce
    9610             :   // an extra load.
    9611         276 :   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
    9612             :        ++UI) {
    9613         336 :     if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
    9614          60 :       continue;
    9615         108 :     if (*UI != N)
    9616           0 :       return SDValue();
    9617             :   }
    9618             : 
    9619         216 :   SDValue Addr = LD->getOperand(1);
    9620         216 :   SDValue Vector = N->getOperand(0);
    9621             :   // Search for a use of the address operand that is an increment.
    9622         108 :   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
    9623         519 :        Addr.getNode()->use_end(); UI != UE; ++UI) {
    9624         129 :     SDNode *User = *UI;
    9625          84 :     if (User->getOpcode() != ISD::ADD
    9626         174 :         || UI.getUse().getResNo() != Addr.getResNo())
    9627         171 :       continue;
    9628             : 
    9629             :     // Check that the add is independent of the load.  Otherwise, folding it
    9630             :     // would create a cycle.
    9631          90 :     if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
    9632           0 :       continue;
    9633             :     // Also check that add is not used in the vector operand.  This would also
    9634             :     // create a cycle.
    9635          91 :     if (User->isPredecessorOf(Vector.getNode()))
    9636           1 :       continue;
    9637             : 
    9638             :     // If the increment is a constant, it must match the memory ref size.
    9639         176 :     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
    9640          66 :     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
    9641          22 :       uint32_t IncVal = CInc->getZExtValue();
    9642          22 :       unsigned NumBytes = VT.getScalarSizeInBits() / 8;
    9643          22 :       if (IncVal != NumBytes)
    9644           1 :         continue;
    9645          21 :       Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
    9646             :     }
    9647             : 
    9648             :     // Finally, check that the vector doesn't depend on the load.
    9649             :     // Again, this would create a cycle.
    9650             :     // The load depending on the vector is fine, as that's the case for the
    9651             :     // LD1*post we'll eventually generate anyway.
    9652          86 :     if (LoadSDN->isPredecessorOf(Vector.getNode()))
    9653           1 :       continue;
    9654             : 
    9655          84 :     SmallVector<SDValue, 8> Ops;
    9656          84 :     Ops.push_back(LD->getOperand(0));  // Chain
    9657          42 :     if (IsLaneOp) {
    9658          22 :       Ops.push_back(Vector);           // The vector to be inserted
    9659          44 :       Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
    9660             :     }
    9661          42 :     Ops.push_back(Addr);
    9662          42 :     Ops.push_back(Inc);
    9663             : 
    9664          42 :     EVT Tys[3] = { VT, MVT::i64, MVT::Other };
    9665          42 :     SDVTList SDTys = DAG.getVTList(Tys);
    9666          42 :     unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
    9667          84 :     SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
    9668             :                                            MemVT,
    9669         168 :                                            LoadSDN->getMemOperand());
    9670             : 
    9671             :     // Update the uses.
    9672             :     SDValue NewResults[] = {
    9673             :         SDValue(LD, 0),            // The result of load
    9674             :         SDValue(UpdN.getNode(), 2) // Chain
    9675         126 :     };
    9676          42 :     DCI.CombineTo(LD, NewResults);
    9677          84 :     DCI.CombineTo(N, SDValue(UpdN.getNode(), 0));     // Dup/Inserted Result
    9678          84 :     DCI.CombineTo(User, SDValue(UpdN.getNode(), 1));  // Write back register
    9679             : 
    9680             :     break;
    9681             :   }
    9682         108 :   return SDValue();
    9683             : }
    9684             : 
    9685             : /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
    9686             : /// address translation.
    9687          25 : static bool performTBISimplification(SDValue Addr,
    9688             :                                      TargetLowering::DAGCombinerInfo &DCI,
    9689             :                                      SelectionDAG &DAG) {
    9690          50 :   APInt DemandedMask = APInt::getLowBitsSet(64, 56);
    9691          50 :   KnownBits Known;
    9692          25 :   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
    9693         100 :                                         !DCI.isBeforeLegalizeOps());
    9694          25 :   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
    9695          25 :   if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
    9696           8 :     DCI.CommitTargetLoweringOpt(TLO);
    9697           8 :     return true;
    9698