1 //===- AArch64InstructionSelector.cpp ----------------------------*- C++ -*-==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This file implements the targeting of the InstructionSelector class for
10 /// AArch64.
11 /// \todo This should be generated by TableGen.
12 //===----------------------------------------------------------------------===//
13 
14 #include "AArch64InstrInfo.h"
15 #include "AArch64MachineFunctionInfo.h"
16 #include "AArch64RegisterBankInfo.h"
17 #include "AArch64RegisterInfo.h"
18 #include "AArch64Subtarget.h"
19 #include "AArch64TargetMachine.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "MCTargetDesc/AArch64MCTargetDesc.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/CodeGen/GlobalISel/InstructionSelector.h"
24 #include "llvm/CodeGen/GlobalISel/InstructionSelectorImpl.h"
25 #include "llvm/CodeGen/GlobalISel/MachineIRBuilder.h"
26 #include "llvm/CodeGen/GlobalISel/MIPatternMatch.h"
27 #include "llvm/CodeGen/GlobalISel/Utils.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineConstantPool.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineOperand.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/TargetOpcodes.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/IR/IntrinsicsAArch64.h"
39 #include "llvm/Pass.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
42 
43 #define DEBUG_TYPE "aarch64-isel"
44 
45 using namespace llvm;
46 using namespace MIPatternMatch;
47 
48 namespace {
49 
50 #define GET_GLOBALISEL_PREDICATE_BITSET
51 #include "AArch64GenGlobalISel.inc"
52 #undef GET_GLOBALISEL_PREDICATE_BITSET
53 
54 class AArch64InstructionSelector : public InstructionSelector {
55 public:
56   AArch64InstructionSelector(const AArch64TargetMachine &TM,
57                              const AArch64Subtarget &STI,
58                              const AArch64RegisterBankInfo &RBI);
59 
60   bool select(MachineInstr &I) override;
61   static const char *getName() { return DEBUG_TYPE; }
62 
63   void setupMF(MachineFunction &MF, GISelKnownBits &KB,
64                CodeGenCoverage &CoverageInfo) override {
65     InstructionSelector::setupMF(MF, KB, CoverageInfo);
66 
67     // hasFnAttribute() is expensive to call on every BRCOND selection, so
68     // cache it here for each run of the selector.
69     ProduceNonFlagSettingCondBr =
70         !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
71     MFReturnAddr = Register();
72 
73     processPHIs(MF);
74   }
75 
76 private:
77   /// tblgen-erated 'select' implementation, used as the initial selector for
78   /// the patterns that don't require complex C++.
79   bool selectImpl(MachineInstr &I, CodeGenCoverage &CoverageInfo) const;
80 
81   // A lowering phase that runs before any selection attempts.
82   // Returns true if the instruction was modified.
83   bool preISelLower(MachineInstr &I);
84 
85   // An early selection function that runs before the selectImpl() call.
86   bool earlySelect(MachineInstr &I) const;
87 
88   // Do some preprocessing of G_PHIs before we begin selection.
89   void processPHIs(MachineFunction &MF);
90 
91   bool earlySelectSHL(MachineInstr &I, MachineRegisterInfo &MRI) const;
92 
93   /// Eliminate same-sized cross-bank copies into stores before selectImpl().
94   bool contractCrossBankCopyIntoStore(MachineInstr &I,
95                                       MachineRegisterInfo &MRI);
96 
97   bool convertPtrAddToAdd(MachineInstr &I, MachineRegisterInfo &MRI);
98 
99   bool selectVaStartAAPCS(MachineInstr &I, MachineFunction &MF,
100                           MachineRegisterInfo &MRI) const;
101   bool selectVaStartDarwin(MachineInstr &I, MachineFunction &MF,
102                            MachineRegisterInfo &MRI) const;
103 
104   bool tryOptAndIntoCompareBranch(MachineInstr *LHS,
105                                   int64_t CmpConstant,
106                                   const CmpInst::Predicate &Pred,
107                                   MachineBasicBlock *DstMBB,
108                                   MachineIRBuilder &MIB) const;
109   bool selectCompareBranch(MachineInstr &I, MachineFunction &MF,
110                            MachineRegisterInfo &MRI) const;
111 
112   bool selectVectorAshrLshr(MachineInstr &I, MachineRegisterInfo &MRI) const;
113   bool selectVectorSHL(MachineInstr &I, MachineRegisterInfo &MRI) const;
114 
115   // Helper to generate an equivalent of scalar_to_vector into a new register,
116   // returned via 'Dst'.
117   MachineInstr *emitScalarToVector(unsigned EltSize,
118                                    const TargetRegisterClass *DstRC,
119                                    Register Scalar,
120                                    MachineIRBuilder &MIRBuilder) const;
121 
122   /// Emit a lane insert into \p DstReg, or a new vector register if None is
123   /// provided.
124   ///
125   /// The lane inserted into is defined by \p LaneIdx. The vector source
126   /// register is given by \p SrcReg. The register containing the element is
127   /// given by \p EltReg.
128   MachineInstr *emitLaneInsert(Optional<Register> DstReg, Register SrcReg,
129                                Register EltReg, unsigned LaneIdx,
130                                const RegisterBank &RB,
131                                MachineIRBuilder &MIRBuilder) const;
132   bool selectInsertElt(MachineInstr &I, MachineRegisterInfo &MRI) const;
133   bool tryOptConstantBuildVec(MachineInstr &MI, LLT DstTy,
134                               MachineRegisterInfo &MRI) const;
135   bool selectBuildVector(MachineInstr &I, MachineRegisterInfo &MRI) const;
136   bool selectMergeValues(MachineInstr &I, MachineRegisterInfo &MRI) const;
137   bool selectUnmergeValues(MachineInstr &I, MachineRegisterInfo &MRI) const;
138 
139   bool selectShuffleVector(MachineInstr &I, MachineRegisterInfo &MRI) const;
140   bool selectExtractElt(MachineInstr &I, MachineRegisterInfo &MRI) const;
141   bool selectConcatVectors(MachineInstr &I, MachineRegisterInfo &MRI) const;
142   bool selectSplitVectorUnmerge(MachineInstr &I,
143                                 MachineRegisterInfo &MRI) const;
144   bool selectIntrinsicWithSideEffects(MachineInstr &I,
145                                       MachineRegisterInfo &MRI) const;
146   bool selectIntrinsic(MachineInstr &I, MachineRegisterInfo &MRI);
147   bool selectVectorICmp(MachineInstr &I, MachineRegisterInfo &MRI) const;
148   bool selectIntrinsicTrunc(MachineInstr &I, MachineRegisterInfo &MRI) const;
149   bool selectIntrinsicRound(MachineInstr &I, MachineRegisterInfo &MRI) const;
150   bool selectJumpTable(MachineInstr &I, MachineRegisterInfo &MRI) const;
151   bool selectBrJT(MachineInstr &I, MachineRegisterInfo &MRI) const;
152   bool selectTLSGlobalValue(MachineInstr &I, MachineRegisterInfo &MRI) const;
153   bool selectReduction(MachineInstr &I, MachineRegisterInfo &MRI) const;
154 
155   unsigned emitConstantPoolEntry(const Constant *CPVal,
156                                  MachineFunction &MF) const;
157   MachineInstr *emitLoadFromConstantPool(const Constant *CPVal,
158                                          MachineIRBuilder &MIRBuilder) const;
159 
160   // Emit a vector concat operation.
161   MachineInstr *emitVectorConcat(Optional<Register> Dst, Register Op1,
162                                  Register Op2,
163                                  MachineIRBuilder &MIRBuilder) const;
164 
165   // Emit an integer compare between LHS and RHS, which checks for Predicate.
166   MachineInstr *emitIntegerCompare(MachineOperand &LHS, MachineOperand &RHS,
167                                    MachineOperand &Predicate,
168                                    MachineIRBuilder &MIRBuilder) const;
169 
170   /// Emit a floating point comparison between \p LHS and \p RHS.
171   MachineInstr *emitFPCompare(Register LHS, Register RHS,
172                               MachineIRBuilder &MIRBuilder) const;
173 
174   MachineInstr *emitInstr(unsigned Opcode,
175                           std::initializer_list<llvm::DstOp> DstOps,
176                           std::initializer_list<llvm::SrcOp> SrcOps,
177                           MachineIRBuilder &MIRBuilder,
178                           const ComplexRendererFns &RenderFns = None) const;
179   /// Helper function to emit a binary operation such as an ADD, ADDS, etc.
180   ///
181   /// This is intended for instructions with the following opcode variants:
182   ///
183   ///  - Xri, Wri (arithmetic immediate form)
184   ///  - Xrs, Wrs (shifted register form)
185   ///  - Xrr, Wrr (register form)
186   ///
187   /// For example, for ADD, we have ADDXri, ADDWri, ADDXrs, etc.
188   ///
189   /// \p AddrModeAndSizeToOpcode must contain each of the opcode variants above
190   /// in a specific order.
191   ///
192   /// Below is an example of the expected input to \p AddrModeAndSizeToOpcode.
193   ///
194   /// \code
195   ///   const std::array<std::array<unsigned, 2>, 3> Table {
196   ///    {{AArch64::ADDXri, AArch64::ADDWri},
197   ///     {AArch64::ADDXrs, AArch64::ADDWrs},
198   ///     {AArch64::ADDXrr, AArch64::ADDWrr}}};
199   /// \endcode
200   ///
201   /// Each row in the table corresponds to a different addressing mode. Each
202   /// column corresponds to a different register size.
203   ///
204   /// \attention Rows must be structured as follows:
205   ///   - Row 0: The ri opcode variants
206   ///   - Row 1: The rs opcode variants
207   ///   - Row 2: The rr opcode variants
208   ///
209   /// \attention Columns must be structured as follows:
210   ///   - Column 0: The 64-bit opcode variants
211   ///   - Column 1: The 32-bit opcode variants
212   ///
213   /// \p Dst is the destination register of the binop to emit.
214   /// \p LHS is the left-hand operand of the binop to emit.
215   /// \p RHS is the right-hand operand of the binop to emit.
216   MachineInstr *emitBinOp(
217       const std::array<std::array<unsigned, 2>, 3> &AddrModeAndSizeToOpcode,
218       Register Dst, MachineOperand &LHS, MachineOperand &RHS,
219       MachineIRBuilder &MIRBuilder) const;
220   MachineInstr *emitADD(Register DefReg, MachineOperand &LHS,
221                         MachineOperand &RHS,
222                         MachineIRBuilder &MIRBuilder) const;
223   MachineInstr *emitADDS(Register Dst, MachineOperand &LHS, MachineOperand &RHS,
224                          MachineIRBuilder &MIRBuilder) const;
225   MachineInstr *emitSUBS(Register Dst, MachineOperand &LHS, MachineOperand &RHS,
226                          MachineIRBuilder &MIRBuilder) const;
227   MachineInstr *emitCMN(MachineOperand &LHS, MachineOperand &RHS,
228                         MachineIRBuilder &MIRBuilder) const;
229   MachineInstr *emitTST(MachineOperand &LHS, MachineOperand &RHS,
230                         MachineIRBuilder &MIRBuilder) const;
231   MachineInstr *emitExtractVectorElt(Optional<Register> DstReg,
232                                      const RegisterBank &DstRB, LLT ScalarTy,
233                                      Register VecReg, unsigned LaneIdx,
234                                      MachineIRBuilder &MIRBuilder) const;
235 
236   /// Helper function for selecting G_FCONSTANT. If the G_FCONSTANT can be
237   /// materialized using a FMOV instruction, then update MI and return it.
238   /// Otherwise, do nothing and return a nullptr.
239   MachineInstr *emitFMovForFConstant(MachineInstr &MI,
240                                      MachineRegisterInfo &MRI) const;
241 
242   /// Emit a CSet for an integer compare.
243   ///
244   /// \p DefReg is expected to be a 32-bit scalar register.
245   MachineInstr *emitCSetForICMP(Register DefReg, unsigned Pred,
246                                 MachineIRBuilder &MIRBuilder) const;
247   /// Emit a CSet for a FP compare.
248   ///
249   /// \p Dst is expected to be a 32-bit scalar register.
250   MachineInstr *emitCSetForFCmp(Register Dst, CmpInst::Predicate Pred,
251                                 MachineIRBuilder &MIRBuilder) const;
252 
253   /// Emit a TB(N)Z instruction which tests \p Bit in \p TestReg.
254   /// \p IsNegative is true if the test should be "not zero".
255   /// This will also optimize the test bit instruction when possible.
256   MachineInstr *emitTestBit(Register TestReg, uint64_t Bit, bool IsNegative,
257                             MachineBasicBlock *DstMBB,
258                             MachineIRBuilder &MIB) const;
259 
260   // Equivalent to the i32shift_a and friends from AArch64InstrInfo.td.
261   // We use these manually instead of using the importer since it doesn't
262   // support SDNodeXForm.
263   ComplexRendererFns selectShiftA_32(const MachineOperand &Root) const;
264   ComplexRendererFns selectShiftB_32(const MachineOperand &Root) const;
265   ComplexRendererFns selectShiftA_64(const MachineOperand &Root) const;
266   ComplexRendererFns selectShiftB_64(const MachineOperand &Root) const;
267 
268   ComplexRendererFns select12BitValueWithLeftShift(uint64_t Immed) const;
269   ComplexRendererFns selectArithImmed(MachineOperand &Root) const;
270   ComplexRendererFns selectNegArithImmed(MachineOperand &Root) const;
271 
272   ComplexRendererFns selectAddrModeUnscaled(MachineOperand &Root,
273                                             unsigned Size) const;
274 
275   ComplexRendererFns selectAddrModeUnscaled8(MachineOperand &Root) const {
276     return selectAddrModeUnscaled(Root, 1);
277   }
278   ComplexRendererFns selectAddrModeUnscaled16(MachineOperand &Root) const {
279     return selectAddrModeUnscaled(Root, 2);
280   }
281   ComplexRendererFns selectAddrModeUnscaled32(MachineOperand &Root) const {
282     return selectAddrModeUnscaled(Root, 4);
283   }
284   ComplexRendererFns selectAddrModeUnscaled64(MachineOperand &Root) const {
285     return selectAddrModeUnscaled(Root, 8);
286   }
287   ComplexRendererFns selectAddrModeUnscaled128(MachineOperand &Root) const {
288     return selectAddrModeUnscaled(Root, 16);
289   }
290 
291   /// Helper to try to fold in a GISEL_ADD_LOW into an immediate, to be used
292   /// from complex pattern matchers like selectAddrModeIndexed().
293   ComplexRendererFns tryFoldAddLowIntoImm(MachineInstr &RootDef, unsigned Size,
294                                           MachineRegisterInfo &MRI) const;
295 
296   ComplexRendererFns selectAddrModeIndexed(MachineOperand &Root,
297                                            unsigned Size) const;
298   template <int Width>
299   ComplexRendererFns selectAddrModeIndexed(MachineOperand &Root) const {
300     return selectAddrModeIndexed(Root, Width / 8);
301   }
302 
303   bool isWorthFoldingIntoExtendedReg(MachineInstr &MI,
304                                      const MachineRegisterInfo &MRI) const;
305   ComplexRendererFns
306   selectAddrModeShiftedExtendXReg(MachineOperand &Root,
307                                   unsigned SizeInBytes) const;
308 
309   /// Returns a \p ComplexRendererFns which contains a base, offset, and whether
310   /// or not a shift + extend should be folded into an addressing mode. Returns
311   /// None when this is not profitable or possible.
312   ComplexRendererFns
313   selectExtendedSHL(MachineOperand &Root, MachineOperand &Base,
314                     MachineOperand &Offset, unsigned SizeInBytes,
315                     bool WantsExt) const;
316   ComplexRendererFns selectAddrModeRegisterOffset(MachineOperand &Root) const;
317   ComplexRendererFns selectAddrModeXRO(MachineOperand &Root,
318                                        unsigned SizeInBytes) const;
319   template <int Width>
320   ComplexRendererFns selectAddrModeXRO(MachineOperand &Root) const {
321     return selectAddrModeXRO(Root, Width / 8);
322   }
323 
324   ComplexRendererFns selectAddrModeWRO(MachineOperand &Root,
325                                        unsigned SizeInBytes) const;
326   template <int Width>
327   ComplexRendererFns selectAddrModeWRO(MachineOperand &Root) const {
328     return selectAddrModeWRO(Root, Width / 8);
329   }
330 
331   ComplexRendererFns selectShiftedRegister(MachineOperand &Root) const;
332 
333   ComplexRendererFns selectArithShiftedRegister(MachineOperand &Root) const {
334     return selectShiftedRegister(Root);
335   }
336 
337   ComplexRendererFns selectLogicalShiftedRegister(MachineOperand &Root) const {
338     // TODO: selectShiftedRegister should allow for rotates on logical shifts.
339     // For now, make them the same. The only difference between the two is that
340     // logical shifts are allowed to fold in rotates. Otherwise, these are
341     // functionally the same.
342     return selectShiftedRegister(Root);
343   }
344 
345   /// Given an extend instruction, determine the correct shift-extend type for
346   /// that instruction.
347   ///
348   /// If the instruction is going to be used in a load or store, pass
349   /// \p IsLoadStore = true.
350   AArch64_AM::ShiftExtendType
351   getExtendTypeForInst(MachineInstr &MI, MachineRegisterInfo &MRI,
352                        bool IsLoadStore = false) const;
353 
354   /// Instructions that accept extend modifiers like UXTW expect the register
355   /// being extended to be a GPR32. Narrow ExtReg to a 32-bit register using a
356   /// subregister copy if necessary. Return either ExtReg, or the result of the
357   /// new copy.
358   Register narrowExtendRegIfNeeded(Register ExtReg,
359                                              MachineIRBuilder &MIB) const;
360   Register widenGPRBankRegIfNeeded(Register Reg, unsigned Size,
361                                    MachineIRBuilder &MIB) const;
362   ComplexRendererFns selectArithExtendedRegister(MachineOperand &Root) const;
363 
364   void renderTruncImm(MachineInstrBuilder &MIB, const MachineInstr &MI,
365                       int OpIdx = -1) const;
366   void renderLogicalImm32(MachineInstrBuilder &MIB, const MachineInstr &I,
367                           int OpIdx = -1) const;
368   void renderLogicalImm64(MachineInstrBuilder &MIB, const MachineInstr &I,
369                           int OpIdx = -1) const;
370 
371   // Materialize a GlobalValue or BlockAddress using a movz+movk sequence.
372   void materializeLargeCMVal(MachineInstr &I, const Value *V,
373                              unsigned OpFlags) const;
374 
375   // Optimization methods.
376   bool tryOptSelect(MachineInstr &MI) const;
377   MachineInstr *tryFoldIntegerCompare(MachineOperand &LHS, MachineOperand &RHS,
378                                       MachineOperand &Predicate,
379                                       MachineIRBuilder &MIRBuilder) const;
380 
381   /// Return true if \p MI is a load or store of \p NumBytes bytes.
382   bool isLoadStoreOfNumBytes(const MachineInstr &MI, unsigned NumBytes) const;
383 
384   /// Returns true if \p MI is guaranteed to have the high-half of a 64-bit
385   /// register zeroed out. In other words, the result of MI has been explicitly
386   /// zero extended.
387   bool isDef32(const MachineInstr &MI) const;
388 
389   const AArch64TargetMachine &TM;
390   const AArch64Subtarget &STI;
391   const AArch64InstrInfo &TII;
392   const AArch64RegisterInfo &TRI;
393   const AArch64RegisterBankInfo &RBI;
394 
395   bool ProduceNonFlagSettingCondBr = false;
396 
397   // Some cached values used during selection.
398   // We use LR as a live-in register, and we keep track of it here as it can be
399   // clobbered by calls.
400   Register MFReturnAddr;
401 
402 #define GET_GLOBALISEL_PREDICATES_DECL
403 #include "AArch64GenGlobalISel.inc"
404 #undef GET_GLOBALISEL_PREDICATES_DECL
405 
406 // We declare the temporaries used by selectImpl() in the class to minimize the
407 // cost of constructing placeholder values.
408 #define GET_GLOBALISEL_TEMPORARIES_DECL
409 #include "AArch64GenGlobalISel.inc"
410 #undef GET_GLOBALISEL_TEMPORARIES_DECL
411 };
412 
413 } // end anonymous namespace
414 
415 #define GET_GLOBALISEL_IMPL
416 #include "AArch64GenGlobalISel.inc"
417 #undef GET_GLOBALISEL_IMPL
418 
419 AArch64InstructionSelector::AArch64InstructionSelector(
420     const AArch64TargetMachine &TM, const AArch64Subtarget &STI,
421     const AArch64RegisterBankInfo &RBI)
422     : InstructionSelector(), TM(TM), STI(STI), TII(*STI.getInstrInfo()),
423       TRI(*STI.getRegisterInfo()), RBI(RBI),
424 #define GET_GLOBALISEL_PREDICATES_INIT
425 #include "AArch64GenGlobalISel.inc"
426 #undef GET_GLOBALISEL_PREDICATES_INIT
427 #define GET_GLOBALISEL_TEMPORARIES_INIT
428 #include "AArch64GenGlobalISel.inc"
429 #undef GET_GLOBALISEL_TEMPORARIES_INIT
430 {
431 }
432 
433 // FIXME: This should be target-independent, inferred from the types declared
434 // for each class in the bank.
435 static const TargetRegisterClass *
436 getRegClassForTypeOnBank(LLT Ty, const RegisterBank &RB,
437                          const RegisterBankInfo &RBI,
438                          bool GetAllRegSet = false) {
439   if (RB.getID() == AArch64::GPRRegBankID) {
440     if (Ty.getSizeInBits() <= 32)
441       return GetAllRegSet ? &AArch64::GPR32allRegClass
442                           : &AArch64::GPR32RegClass;
443     if (Ty.getSizeInBits() == 64)
444       return GetAllRegSet ? &AArch64::GPR64allRegClass
445                           : &AArch64::GPR64RegClass;
446     return nullptr;
447   }
448 
449   if (RB.getID() == AArch64::FPRRegBankID) {
450     if (Ty.getSizeInBits() <= 16)
451       return &AArch64::FPR16RegClass;
452     if (Ty.getSizeInBits() == 32)
453       return &AArch64::FPR32RegClass;
454     if (Ty.getSizeInBits() == 64)
455       return &AArch64::FPR64RegClass;
456     if (Ty.getSizeInBits() == 128)
457       return &AArch64::FPR128RegClass;
458     return nullptr;
459   }
460 
461   return nullptr;
462 }
463 
464 /// Given a register bank, and size in bits, return the smallest register class
465 /// that can represent that combination.
466 static const TargetRegisterClass *
467 getMinClassForRegBank(const RegisterBank &RB, unsigned SizeInBits,
468                       bool GetAllRegSet = false) {
469   unsigned RegBankID = RB.getID();
470 
471   if (RegBankID == AArch64::GPRRegBankID) {
472     if (SizeInBits <= 32)
473       return GetAllRegSet ? &AArch64::GPR32allRegClass
474                           : &AArch64::GPR32RegClass;
475     if (SizeInBits == 64)
476       return GetAllRegSet ? &AArch64::GPR64allRegClass
477                           : &AArch64::GPR64RegClass;
478   }
479 
480   if (RegBankID == AArch64::FPRRegBankID) {
481     switch (SizeInBits) {
482     default:
483       return nullptr;
484     case 8:
485       return &AArch64::FPR8RegClass;
486     case 16:
487       return &AArch64::FPR16RegClass;
488     case 32:
489       return &AArch64::FPR32RegClass;
490     case 64:
491       return &AArch64::FPR64RegClass;
492     case 128:
493       return &AArch64::FPR128RegClass;
494     }
495   }
496 
497   return nullptr;
498 }
499 
500 /// Returns the correct subregister to use for a given register class.
501 static bool getSubRegForClass(const TargetRegisterClass *RC,
502                               const TargetRegisterInfo &TRI, unsigned &SubReg) {
503   switch (TRI.getRegSizeInBits(*RC)) {
504   case 8:
505     SubReg = AArch64::bsub;
506     break;
507   case 16:
508     SubReg = AArch64::hsub;
509     break;
510   case 32:
511     if (RC != &AArch64::FPR32RegClass)
512       SubReg = AArch64::sub_32;
513     else
514       SubReg = AArch64::ssub;
515     break;
516   case 64:
517     SubReg = AArch64::dsub;
518     break;
519   default:
520     LLVM_DEBUG(
521         dbgs() << "Couldn't find appropriate subregister for register class.");
522     return false;
523   }
524 
525   return true;
526 }
527 
528 /// Returns the minimum size the given register bank can hold.
529 static unsigned getMinSizeForRegBank(const RegisterBank &RB) {
530   switch (RB.getID()) {
531   case AArch64::GPRRegBankID:
532     return 32;
533   case AArch64::FPRRegBankID:
534     return 8;
535   default:
536     llvm_unreachable("Tried to get minimum size for unknown register bank.");
537   }
538 }
539 
540 static Optional<uint64_t> getImmedFromMO(const MachineOperand &Root) {
541   auto &MI = *Root.getParent();
542   auto &MBB = *MI.getParent();
543   auto &MF = *MBB.getParent();
544   auto &MRI = MF.getRegInfo();
545   uint64_t Immed;
546   if (Root.isImm())
547     Immed = Root.getImm();
548   else if (Root.isCImm())
549     Immed = Root.getCImm()->getZExtValue();
550   else if (Root.isReg()) {
551     auto ValAndVReg =
552         getConstantVRegValWithLookThrough(Root.getReg(), MRI, true);
553     if (!ValAndVReg)
554       return None;
555     Immed = ValAndVReg->Value;
556   } else
557     return None;
558   return Immed;
559 }
560 
561 /// Check whether \p I is a currently unsupported binary operation:
562 /// - it has an unsized type
563 /// - an operand is not a vreg
564 /// - all operands are not in the same bank
565 /// These are checks that should someday live in the verifier, but right now,
566 /// these are mostly limitations of the aarch64 selector.
567 static bool unsupportedBinOp(const MachineInstr &I,
568                              const AArch64RegisterBankInfo &RBI,
569                              const MachineRegisterInfo &MRI,
570                              const AArch64RegisterInfo &TRI) {
571   LLT Ty = MRI.getType(I.getOperand(0).getReg());
572   if (!Ty.isValid()) {
573     LLVM_DEBUG(dbgs() << "Generic binop register should be typed\n");
574     return true;
575   }
576 
577   const RegisterBank *PrevOpBank = nullptr;
578   for (auto &MO : I.operands()) {
579     // FIXME: Support non-register operands.
580     if (!MO.isReg()) {
581       LLVM_DEBUG(dbgs() << "Generic inst non-reg operands are unsupported\n");
582       return true;
583     }
584 
585     // FIXME: Can generic operations have physical registers operands? If
586     // so, this will need to be taught about that, and we'll need to get the
587     // bank out of the minimal class for the register.
588     // Either way, this needs to be documented (and possibly verified).
589     if (!Register::isVirtualRegister(MO.getReg())) {
590       LLVM_DEBUG(dbgs() << "Generic inst has physical register operand\n");
591       return true;
592     }
593 
594     const RegisterBank *OpBank = RBI.getRegBank(MO.getReg(), MRI, TRI);
595     if (!OpBank) {
596       LLVM_DEBUG(dbgs() << "Generic register has no bank or class\n");
597       return true;
598     }
599 
600     if (PrevOpBank && OpBank != PrevOpBank) {
601       LLVM_DEBUG(dbgs() << "Generic inst operands have different banks\n");
602       return true;
603     }
604     PrevOpBank = OpBank;
605   }
606   return false;
607 }
608 
609 /// Select the AArch64 opcode for the basic binary operation \p GenericOpc
610 /// (such as G_OR or G_SDIV), appropriate for the register bank \p RegBankID
611 /// and of size \p OpSize.
612 /// \returns \p GenericOpc if the combination is unsupported.
613 static unsigned selectBinaryOp(unsigned GenericOpc, unsigned RegBankID,
614                                unsigned OpSize) {
615   switch (RegBankID) {
616   case AArch64::GPRRegBankID:
617     if (OpSize == 32) {
618       switch (GenericOpc) {
619       case TargetOpcode::G_SHL:
620         return AArch64::LSLVWr;
621       case TargetOpcode::G_LSHR:
622         return AArch64::LSRVWr;
623       case TargetOpcode::G_ASHR:
624         return AArch64::ASRVWr;
625       default:
626         return GenericOpc;
627       }
628     } else if (OpSize == 64) {
629       switch (GenericOpc) {
630       case TargetOpcode::G_PTR_ADD:
631         return AArch64::ADDXrr;
632       case TargetOpcode::G_SHL:
633         return AArch64::LSLVXr;
634       case TargetOpcode::G_LSHR:
635         return AArch64::LSRVXr;
636       case TargetOpcode::G_ASHR:
637         return AArch64::ASRVXr;
638       default:
639         return GenericOpc;
640       }
641     }
642     break;
643   case AArch64::FPRRegBankID:
644     switch (OpSize) {
645     case 32:
646       switch (GenericOpc) {
647       case TargetOpcode::G_FADD:
648         return AArch64::FADDSrr;
649       case TargetOpcode::G_FSUB:
650         return AArch64::FSUBSrr;
651       case TargetOpcode::G_FMUL:
652         return AArch64::FMULSrr;
653       case TargetOpcode::G_FDIV:
654         return AArch64::FDIVSrr;
655       default:
656         return GenericOpc;
657       }
658     case 64:
659       switch (GenericOpc) {
660       case TargetOpcode::G_FADD:
661         return AArch64::FADDDrr;
662       case TargetOpcode::G_FSUB:
663         return AArch64::FSUBDrr;
664       case TargetOpcode::G_FMUL:
665         return AArch64::FMULDrr;
666       case TargetOpcode::G_FDIV:
667         return AArch64::FDIVDrr;
668       case TargetOpcode::G_OR:
669         return AArch64::ORRv8i8;
670       default:
671         return GenericOpc;
672       }
673     }
674     break;
675   }
676   return GenericOpc;
677 }
678 
679 /// Select the AArch64 opcode for the G_LOAD or G_STORE operation \p GenericOpc,
680 /// appropriate for the (value) register bank \p RegBankID and of memory access
681 /// size \p OpSize.  This returns the variant with the base+unsigned-immediate
682 /// addressing mode (e.g., LDRXui).
683 /// \returns \p GenericOpc if the combination is unsupported.
684 static unsigned selectLoadStoreUIOp(unsigned GenericOpc, unsigned RegBankID,
685                                     unsigned OpSize) {
686   const bool isStore = GenericOpc == TargetOpcode::G_STORE;
687   switch (RegBankID) {
688   case AArch64::GPRRegBankID:
689     switch (OpSize) {
690     case 8:
691       return isStore ? AArch64::STRBBui : AArch64::LDRBBui;
692     case 16:
693       return isStore ? AArch64::STRHHui : AArch64::LDRHHui;
694     case 32:
695       return isStore ? AArch64::STRWui : AArch64::LDRWui;
696     case 64:
697       return isStore ? AArch64::STRXui : AArch64::LDRXui;
698     }
699     break;
700   case AArch64::FPRRegBankID:
701     switch (OpSize) {
702     case 8:
703       return isStore ? AArch64::STRBui : AArch64::LDRBui;
704     case 16:
705       return isStore ? AArch64::STRHui : AArch64::LDRHui;
706     case 32:
707       return isStore ? AArch64::STRSui : AArch64::LDRSui;
708     case 64:
709       return isStore ? AArch64::STRDui : AArch64::LDRDui;
710     }
711     break;
712   }
713   return GenericOpc;
714 }
715 
716 #ifndef NDEBUG
717 /// Helper function that verifies that we have a valid copy at the end of
718 /// selectCopy. Verifies that the source and dest have the expected sizes and
719 /// then returns true.
720 static bool isValidCopy(const MachineInstr &I, const RegisterBank &DstBank,
721                         const MachineRegisterInfo &MRI,
722                         const TargetRegisterInfo &TRI,
723                         const RegisterBankInfo &RBI) {
724   const Register DstReg = I.getOperand(0).getReg();
725   const Register SrcReg = I.getOperand(1).getReg();
726   const unsigned DstSize = RBI.getSizeInBits(DstReg, MRI, TRI);
727   const unsigned SrcSize = RBI.getSizeInBits(SrcReg, MRI, TRI);
728 
729   // Make sure the size of the source and dest line up.
730   assert(
731       (DstSize == SrcSize ||
732        // Copies are a mean to setup initial types, the number of
733        // bits may not exactly match.
734        (Register::isPhysicalRegister(SrcReg) && DstSize <= SrcSize) ||
735        // Copies are a mean to copy bits around, as long as we are
736        // on the same register class, that's fine. Otherwise, that
737        // means we need some SUBREG_TO_REG or AND & co.
738        (((DstSize + 31) / 32 == (SrcSize + 31) / 32) && DstSize > SrcSize)) &&
739       "Copy with different width?!");
740 
741   // Check the size of the destination.
742   assert((DstSize <= 64 || DstBank.getID() == AArch64::FPRRegBankID) &&
743          "GPRs cannot get more than 64-bit width values");
744 
745   return true;
746 }
747 #endif
748 
749 /// Helper function for selectCopy. Inserts a subregister copy from \p SrcReg
750 /// to \p *To.
751 ///
752 /// E.g "To = COPY SrcReg:SubReg"
753 static bool copySubReg(MachineInstr &I, MachineRegisterInfo &MRI,
754                        const RegisterBankInfo &RBI, Register SrcReg,
755                        const TargetRegisterClass *To, unsigned SubReg) {
756   assert(SrcReg.isValid() && "Expected a valid source register?");
757   assert(To && "Destination register class cannot be null");
758   assert(SubReg && "Expected a valid subregister");
759 
760   MachineIRBuilder MIB(I);
761   auto SubRegCopy =
762       MIB.buildInstr(TargetOpcode::COPY, {To}, {}).addReg(SrcReg, 0, SubReg);
763   MachineOperand &RegOp = I.getOperand(1);
764   RegOp.setReg(SubRegCopy.getReg(0));
765 
766   // It's possible that the destination register won't be constrained. Make
767   // sure that happens.
768   if (!Register::isPhysicalRegister(I.getOperand(0).getReg()))
769     RBI.constrainGenericRegister(I.getOperand(0).getReg(), *To, MRI);
770 
771   return true;
772 }
773 
774 /// Helper function to get the source and destination register classes for a
775 /// copy. Returns a std::pair containing the source register class for the
776 /// copy, and the destination register class for the copy. If a register class
777 /// cannot be determined, then it will be nullptr.
778 static std::pair<const TargetRegisterClass *, const TargetRegisterClass *>
779 getRegClassesForCopy(MachineInstr &I, const TargetInstrInfo &TII,
780                      MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
781                      const RegisterBankInfo &RBI) {
782   Register DstReg = I.getOperand(0).getReg();
783   Register SrcReg = I.getOperand(1).getReg();
784   const RegisterBank &DstRegBank = *RBI.getRegBank(DstReg, MRI, TRI);
785   const RegisterBank &SrcRegBank = *RBI.getRegBank(SrcReg, MRI, TRI);
786   unsigned DstSize = RBI.getSizeInBits(DstReg, MRI, TRI);
787   unsigned SrcSize = RBI.getSizeInBits(SrcReg, MRI, TRI);
788 
789   // Special casing for cross-bank copies of s1s. We can technically represent
790   // a 1-bit value with any size of register. The minimum size for a GPR is 32
791   // bits. So, we need to put the FPR on 32 bits as well.
792   //
793   // FIXME: I'm not sure if this case holds true outside of copies. If it does,
794   // then we can pull it into the helpers that get the appropriate class for a
795   // register bank. Or make a new helper that carries along some constraint
796   // information.
797   if (SrcRegBank != DstRegBank && (DstSize == 1 && SrcSize == 1))
798     SrcSize = DstSize = 32;
799 
800   return {getMinClassForRegBank(SrcRegBank, SrcSize, true),
801           getMinClassForRegBank(DstRegBank, DstSize, true)};
802 }
803 
804 static bool selectCopy(MachineInstr &I, const TargetInstrInfo &TII,
805                        MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI,
806                        const RegisterBankInfo &RBI) {
807   Register DstReg = I.getOperand(0).getReg();
808   Register SrcReg = I.getOperand(1).getReg();
809   const RegisterBank &DstRegBank = *RBI.getRegBank(DstReg, MRI, TRI);
810   const RegisterBank &SrcRegBank = *RBI.getRegBank(SrcReg, MRI, TRI);
811 
812   // Find the correct register classes for the source and destination registers.
813   const TargetRegisterClass *SrcRC;
814   const TargetRegisterClass *DstRC;
815   std::tie(SrcRC, DstRC) = getRegClassesForCopy(I, TII, MRI, TRI, RBI);
816 
817   if (!DstRC) {
818     LLVM_DEBUG(dbgs() << "Unexpected dest size "
819                       << RBI.getSizeInBits(DstReg, MRI, TRI) << '\n');
820     return false;
821   }
822 
823   // A couple helpers below, for making sure that the copy we produce is valid.
824 
825   // Set to true if we insert a SUBREG_TO_REG. If we do this, then we don't want
826   // to verify that the src and dst are the same size, since that's handled by
827   // the SUBREG_TO_REG.
828   bool KnownValid = false;
829 
830   // Returns true, or asserts if something we don't expect happens. Instead of
831   // returning true, we return isValidCopy() to ensure that we verify the
832   // result.
833   auto CheckCopy = [&]() {
834     // If we have a bitcast or something, we can't have physical registers.
835     assert((I.isCopy() ||
836             (!Register::isPhysicalRegister(I.getOperand(0).getReg()) &&
837              !Register::isPhysicalRegister(I.getOperand(1).getReg()))) &&
838            "No phys reg on generic operator!");
839     bool ValidCopy = true;
840 #ifndef NDEBUG
841     ValidCopy = KnownValid || isValidCopy(I, DstRegBank, MRI, TRI, RBI);
842     assert(ValidCopy && "Invalid copy.");
843 #endif
844     return ValidCopy;
845   };
846 
847   // Is this a copy? If so, then we may need to insert a subregister copy.
848   if (I.isCopy()) {
849     // Yes. Check if there's anything to fix up.
850     if (!SrcRC) {
851       LLVM_DEBUG(dbgs() << "Couldn't determine source register class\n");
852       return false;
853     }
854 
855     unsigned SrcSize = TRI.getRegSizeInBits(*SrcRC);
856     unsigned DstSize = TRI.getRegSizeInBits(*DstRC);
857     unsigned SubReg;
858 
859     // If the source bank doesn't support a subregister copy small enough,
860     // then we first need to copy to the destination bank.
861     if (getMinSizeForRegBank(SrcRegBank) > DstSize) {
862       const TargetRegisterClass *DstTempRC =
863           getMinClassForRegBank(DstRegBank, SrcSize, /* GetAllRegSet */ true);
864       getSubRegForClass(DstRC, TRI, SubReg);
865 
866       MachineIRBuilder MIB(I);
867       auto Copy = MIB.buildCopy({DstTempRC}, {SrcReg});
868       copySubReg(I, MRI, RBI, Copy.getReg(0), DstRC, SubReg);
869     } else if (SrcSize > DstSize) {
870       // If the source register is bigger than the destination we need to
871       // perform a subregister copy.
872       const TargetRegisterClass *SubRegRC =
873           getMinClassForRegBank(SrcRegBank, DstSize, /* GetAllRegSet */ true);
874       getSubRegForClass(SubRegRC, TRI, SubReg);
875       copySubReg(I, MRI, RBI, SrcReg, DstRC, SubReg);
876     } else if (DstSize > SrcSize) {
877       // If the destination register is bigger than the source we need to do
878       // a promotion using SUBREG_TO_REG.
879       const TargetRegisterClass *PromotionRC =
880           getMinClassForRegBank(SrcRegBank, DstSize, /* GetAllRegSet */ true);
881       getSubRegForClass(SrcRC, TRI, SubReg);
882 
883       Register PromoteReg = MRI.createVirtualRegister(PromotionRC);
884       BuildMI(*I.getParent(), I, I.getDebugLoc(),
885               TII.get(AArch64::SUBREG_TO_REG), PromoteReg)
886           .addImm(0)
887           .addUse(SrcReg)
888           .addImm(SubReg);
889       MachineOperand &RegOp = I.getOperand(1);
890       RegOp.setReg(PromoteReg);
891 
892       // Promise that the copy is implicitly validated by the SUBREG_TO_REG.
893       KnownValid = true;
894     }
895 
896     // If the destination is a physical register, then there's nothing to
897     // change, so we're done.
898     if (Register::isPhysicalRegister(DstReg))
899       return CheckCopy();
900   }
901 
902   // No need to constrain SrcReg. It will get constrained when we hit another
903   // of its use or its defs. Copies do not have constraints.
904   if (!RBI.constrainGenericRegister(DstReg, *DstRC, MRI)) {
905     LLVM_DEBUG(dbgs() << "Failed to constrain " << TII.getName(I.getOpcode())
906                       << " operand\n");
907     return false;
908   }
909   I.setDesc(TII.get(AArch64::COPY));
910   return CheckCopy();
911 }
912 
913 static unsigned selectFPConvOpc(unsigned GenericOpc, LLT DstTy, LLT SrcTy) {
914   if (!DstTy.isScalar() || !SrcTy.isScalar())
915     return GenericOpc;
916 
917   const unsigned DstSize = DstTy.getSizeInBits();
918   const unsigned SrcSize = SrcTy.getSizeInBits();
919 
920   switch (DstSize) {
921   case 32:
922     switch (SrcSize) {
923     case 32:
924       switch (GenericOpc) {
925       case TargetOpcode::G_SITOFP:
926         return AArch64::SCVTFUWSri;
927       case TargetOpcode::G_UITOFP:
928         return AArch64::UCVTFUWSri;
929       case TargetOpcode::G_FPTOSI:
930         return AArch64::FCVTZSUWSr;
931       case TargetOpcode::G_FPTOUI:
932         return AArch64::FCVTZUUWSr;
933       default:
934         return GenericOpc;
935       }
936     case 64:
937       switch (GenericOpc) {
938       case TargetOpcode::G_SITOFP:
939         return AArch64::SCVTFUXSri;
940       case TargetOpcode::G_UITOFP:
941         return AArch64::UCVTFUXSri;
942       case TargetOpcode::G_FPTOSI:
943         return AArch64::FCVTZSUWDr;
944       case TargetOpcode::G_FPTOUI:
945         return AArch64::FCVTZUUWDr;
946       default:
947         return GenericOpc;
948       }
949     default:
950       return GenericOpc;
951     }
952   case 64:
953     switch (SrcSize) {
954     case 32:
955       switch (GenericOpc) {
956       case TargetOpcode::G_SITOFP:
957         return AArch64::SCVTFUWDri;
958       case TargetOpcode::G_UITOFP:
959         return AArch64::UCVTFUWDri;
960       case TargetOpcode::G_FPTOSI:
961         return AArch64::FCVTZSUXSr;
962       case TargetOpcode::G_FPTOUI:
963         return AArch64::FCVTZUUXSr;
964       default:
965         return GenericOpc;
966       }
967     case 64:
968       switch (GenericOpc) {
969       case TargetOpcode::G_SITOFP:
970         return AArch64::SCVTFUXDri;
971       case TargetOpcode::G_UITOFP:
972         return AArch64::UCVTFUXDri;
973       case TargetOpcode::G_FPTOSI:
974         return AArch64::FCVTZSUXDr;
975       case TargetOpcode::G_FPTOUI:
976         return AArch64::FCVTZUUXDr;
977       default:
978         return GenericOpc;
979       }
980     default:
981       return GenericOpc;
982     }
983   default:
984     return GenericOpc;
985   };
986   return GenericOpc;
987 }
988 
989 static unsigned selectSelectOpc(MachineInstr &I, MachineRegisterInfo &MRI,
990                                 const RegisterBankInfo &RBI) {
991   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
992   bool IsFP = (RBI.getRegBank(I.getOperand(0).getReg(), MRI, TRI)->getID() !=
993                AArch64::GPRRegBankID);
994   LLT Ty = MRI.getType(I.getOperand(0).getReg());
995   if (Ty == LLT::scalar(32))
996     return IsFP ? AArch64::FCSELSrrr : AArch64::CSELWr;
997   else if (Ty == LLT::scalar(64) || Ty == LLT::pointer(0, 64))
998     return IsFP ? AArch64::FCSELDrrr : AArch64::CSELXr;
999   return 0;
1000 }
1001 
1002 /// Returns true if \p P is an unsigned integer comparison predicate.
1003 static bool isUnsignedICMPPred(const CmpInst::Predicate P) {
1004   switch (P) {
1005   default:
1006     return false;
1007   case CmpInst::ICMP_UGT:
1008   case CmpInst::ICMP_UGE:
1009   case CmpInst::ICMP_ULT:
1010   case CmpInst::ICMP_ULE:
1011     return true;
1012   }
1013 }
1014 
1015 static AArch64CC::CondCode changeICMPPredToAArch64CC(CmpInst::Predicate P) {
1016   switch (P) {
1017   default:
1018     llvm_unreachable("Unknown condition code!");
1019   case CmpInst::ICMP_NE:
1020     return AArch64CC::NE;
1021   case CmpInst::ICMP_EQ:
1022     return AArch64CC::EQ;
1023   case CmpInst::ICMP_SGT:
1024     return AArch64CC::GT;
1025   case CmpInst::ICMP_SGE:
1026     return AArch64CC::GE;
1027   case CmpInst::ICMP_SLT:
1028     return AArch64CC::LT;
1029   case CmpInst::ICMP_SLE:
1030     return AArch64CC::LE;
1031   case CmpInst::ICMP_UGT:
1032     return AArch64CC::HI;
1033   case CmpInst::ICMP_UGE:
1034     return AArch64CC::HS;
1035   case CmpInst::ICMP_ULT:
1036     return AArch64CC::LO;
1037   case CmpInst::ICMP_ULE:
1038     return AArch64CC::LS;
1039   }
1040 }
1041 
1042 static void changeFCMPPredToAArch64CC(CmpInst::Predicate P,
1043                                       AArch64CC::CondCode &CondCode,
1044                                       AArch64CC::CondCode &CondCode2) {
1045   CondCode2 = AArch64CC::AL;
1046   switch (P) {
1047   default:
1048     llvm_unreachable("Unknown FP condition!");
1049   case CmpInst::FCMP_OEQ:
1050     CondCode = AArch64CC::EQ;
1051     break;
1052   case CmpInst::FCMP_OGT:
1053     CondCode = AArch64CC::GT;
1054     break;
1055   case CmpInst::FCMP_OGE:
1056     CondCode = AArch64CC::GE;
1057     break;
1058   case CmpInst::FCMP_OLT:
1059     CondCode = AArch64CC::MI;
1060     break;
1061   case CmpInst::FCMP_OLE:
1062     CondCode = AArch64CC::LS;
1063     break;
1064   case CmpInst::FCMP_ONE:
1065     CondCode = AArch64CC::MI;
1066     CondCode2 = AArch64CC::GT;
1067     break;
1068   case CmpInst::FCMP_ORD:
1069     CondCode = AArch64CC::VC;
1070     break;
1071   case CmpInst::FCMP_UNO:
1072     CondCode = AArch64CC::VS;
1073     break;
1074   case CmpInst::FCMP_UEQ:
1075     CondCode = AArch64CC::EQ;
1076     CondCode2 = AArch64CC::VS;
1077     break;
1078   case CmpInst::FCMP_UGT:
1079     CondCode = AArch64CC::HI;
1080     break;
1081   case CmpInst::FCMP_UGE:
1082     CondCode = AArch64CC::PL;
1083     break;
1084   case CmpInst::FCMP_ULT:
1085     CondCode = AArch64CC::LT;
1086     break;
1087   case CmpInst::FCMP_ULE:
1088     CondCode = AArch64CC::LE;
1089     break;
1090   case CmpInst::FCMP_UNE:
1091     CondCode = AArch64CC::NE;
1092     break;
1093   }
1094 }
1095 
1096 /// Return a register which can be used as a bit to test in a TB(N)Z.
1097 static Register getTestBitReg(Register Reg, uint64_t &Bit, bool &Invert,
1098                               MachineRegisterInfo &MRI) {
1099   assert(Reg.isValid() && "Expected valid register!");
1100   while (MachineInstr *MI = getDefIgnoringCopies(Reg, MRI)) {
1101     unsigned Opc = MI->getOpcode();
1102 
1103     if (!MI->getOperand(0).isReg() ||
1104         !MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()))
1105       break;
1106 
1107     // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
1108     //
1109     // (tbz (trunc x), b) -> (tbz x, b) is always safe, because the bit number
1110     // on the truncated x is the same as the bit number on x.
1111     if (Opc == TargetOpcode::G_ANYEXT || Opc == TargetOpcode::G_ZEXT ||
1112         Opc == TargetOpcode::G_TRUNC) {
1113       Register NextReg = MI->getOperand(1).getReg();
1114       // Did we find something worth folding?
1115       if (!NextReg.isValid() || !MRI.hasOneNonDBGUse(NextReg))
1116         break;
1117 
1118       // NextReg is worth folding. Keep looking.
1119       Reg = NextReg;
1120       continue;
1121     }
1122 
1123     // Attempt to find a suitable operation with a constant on one side.
1124     Optional<uint64_t> C;
1125     Register TestReg;
1126     switch (Opc) {
1127     default:
1128       break;
1129     case TargetOpcode::G_AND:
1130     case TargetOpcode::G_XOR: {
1131       TestReg = MI->getOperand(1).getReg();
1132       Register ConstantReg = MI->getOperand(2).getReg();
1133       auto VRegAndVal = getConstantVRegValWithLookThrough(ConstantReg, MRI);
1134       if (!VRegAndVal) {
1135         // AND commutes, check the other side for a constant.
1136         // FIXME: Can we canonicalize the constant so that it's always on the
1137         // same side at some point earlier?
1138         std::swap(ConstantReg, TestReg);
1139         VRegAndVal = getConstantVRegValWithLookThrough(ConstantReg, MRI);
1140       }
1141       if (VRegAndVal)
1142         C = VRegAndVal->Value;
1143       break;
1144     }
1145     case TargetOpcode::G_ASHR:
1146     case TargetOpcode::G_LSHR:
1147     case TargetOpcode::G_SHL: {
1148       TestReg = MI->getOperand(1).getReg();
1149       auto VRegAndVal =
1150           getConstantVRegValWithLookThrough(MI->getOperand(2).getReg(), MRI);
1151       if (VRegAndVal)
1152         C = VRegAndVal->Value;
1153       break;
1154     }
1155     }
1156 
1157     // Didn't find a constant or viable register. Bail out of the loop.
1158     if (!C || !TestReg.isValid())
1159       break;
1160 
1161     // We found a suitable instruction with a constant. Check to see if we can
1162     // walk through the instruction.
1163     Register NextReg;
1164     unsigned TestRegSize = MRI.getType(TestReg).getSizeInBits();
1165     switch (Opc) {
1166     default:
1167       break;
1168     case TargetOpcode::G_AND:
1169       // (tbz (and x, m), b) -> (tbz x, b) when the b-th bit of m is set.
1170       if ((*C >> Bit) & 1)
1171         NextReg = TestReg;
1172       break;
1173     case TargetOpcode::G_SHL:
1174       // (tbz (shl x, c), b) -> (tbz x, b-c) when b-c is positive and fits in
1175       // the type of the register.
1176       if (*C <= Bit && (Bit - *C) < TestRegSize) {
1177         NextReg = TestReg;
1178         Bit = Bit - *C;
1179       }
1180       break;
1181     case TargetOpcode::G_ASHR:
1182       // (tbz (ashr x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits
1183       // in x
1184       NextReg = TestReg;
1185       Bit = Bit + *C;
1186       if (Bit >= TestRegSize)
1187         Bit = TestRegSize - 1;
1188       break;
1189     case TargetOpcode::G_LSHR:
1190       // (tbz (lshr x, c), b) -> (tbz x, b+c) when b + c is < # bits in x
1191       if ((Bit + *C) < TestRegSize) {
1192         NextReg = TestReg;
1193         Bit = Bit + *C;
1194       }
1195       break;
1196     case TargetOpcode::G_XOR:
1197       // We can walk through a G_XOR by inverting whether we use tbz/tbnz when
1198       // appropriate.
1199       //
1200       // e.g. If x' = xor x, c, and the b-th bit is set in c then
1201       //
1202       // tbz x', b -> tbnz x, b
1203       //
1204       // Because x' only has the b-th bit set if x does not.
1205       if ((*C >> Bit) & 1)
1206         Invert = !Invert;
1207       NextReg = TestReg;
1208       break;
1209     }
1210 
1211     // Check if we found anything worth folding.
1212     if (!NextReg.isValid())
1213       return Reg;
1214     Reg = NextReg;
1215   }
1216 
1217   return Reg;
1218 }
1219 
1220 MachineInstr *AArch64InstructionSelector::emitTestBit(
1221     Register TestReg, uint64_t Bit, bool IsNegative, MachineBasicBlock *DstMBB,
1222     MachineIRBuilder &MIB) const {
1223   assert(TestReg.isValid());
1224   assert(ProduceNonFlagSettingCondBr &&
1225          "Cannot emit TB(N)Z with speculation tracking!");
1226   MachineRegisterInfo &MRI = *MIB.getMRI();
1227 
1228   // Attempt to optimize the test bit by walking over instructions.
1229   TestReg = getTestBitReg(TestReg, Bit, IsNegative, MRI);
1230   LLT Ty = MRI.getType(TestReg);
1231   unsigned Size = Ty.getSizeInBits();
1232   assert(!Ty.isVector() && "Expected a scalar!");
1233   assert(Bit < 64 && "Bit is too large!");
1234 
1235   // When the test register is a 64-bit register, we have to narrow to make
1236   // TBNZW work.
1237   bool UseWReg = Bit < 32;
1238   unsigned NecessarySize = UseWReg ? 32 : 64;
1239   if (Size < NecessarySize)
1240     TestReg = widenGPRBankRegIfNeeded(TestReg, NecessarySize, MIB);
1241   else if (Size > NecessarySize)
1242     TestReg = narrowExtendRegIfNeeded(TestReg, MIB);
1243 
1244   static const unsigned OpcTable[2][2] = {{AArch64::TBZX, AArch64::TBNZX},
1245                                           {AArch64::TBZW, AArch64::TBNZW}};
1246   unsigned Opc = OpcTable[UseWReg][IsNegative];
1247   auto TestBitMI =
1248       MIB.buildInstr(Opc).addReg(TestReg).addImm(Bit).addMBB(DstMBB);
1249   constrainSelectedInstRegOperands(*TestBitMI, TII, TRI, RBI);
1250   return &*TestBitMI;
1251 }
1252 
1253 bool AArch64InstructionSelector::tryOptAndIntoCompareBranch(
1254     MachineInstr *AndInst, int64_t CmpConstant, const CmpInst::Predicate &Pred,
1255     MachineBasicBlock *DstMBB, MachineIRBuilder &MIB) const {
1256   // Given something like this:
1257   //
1258   //  %x = ...Something...
1259   //  %one = G_CONSTANT i64 1
1260   //  %zero = G_CONSTANT i64 0
1261   //  %and = G_AND %x, %one
1262   //  %cmp = G_ICMP intpred(ne), %and, %zero
1263   //  %cmp_trunc = G_TRUNC %cmp
1264   //  G_BRCOND %cmp_trunc, %bb.3
1265   //
1266   // We want to try and fold the AND into the G_BRCOND and produce either a
1267   // TBNZ (when we have intpred(ne)) or a TBZ (when we have intpred(eq)).
1268   //
1269   // In this case, we'd get
1270   //
1271   // TBNZ %x %bb.3
1272   //
1273   if (!AndInst || AndInst->getOpcode() != TargetOpcode::G_AND)
1274     return false;
1275 
1276   // Need to be comparing against 0 to fold.
1277   if (CmpConstant != 0)
1278     return false;
1279 
1280   MachineRegisterInfo &MRI = *MIB.getMRI();
1281 
1282   // Only support EQ and NE. If we have LT, then it *is* possible to fold, but
1283   // we don't want to do this. When we have an AND and LT, we need a TST/ANDS,
1284   // so folding would be redundant.
1285   if (Pred != CmpInst::Predicate::ICMP_EQ &&
1286       Pred != CmpInst::Predicate::ICMP_NE)
1287     return false;
1288 
1289   // Check if the AND has a constant on its RHS which we can use as a mask.
1290   // If it's a power of 2, then it's the same as checking a specific bit.
1291   // (e.g, ANDing with 8 == ANDing with 000...100 == testing if bit 3 is set)
1292   auto MaybeBit =
1293       getConstantVRegValWithLookThrough(AndInst->getOperand(2).getReg(), MRI);
1294   if (!MaybeBit || !isPowerOf2_64(MaybeBit->Value))
1295     return false;
1296 
1297   uint64_t Bit = Log2_64(static_cast<uint64_t>(MaybeBit->Value));
1298   Register TestReg = AndInst->getOperand(1).getReg();
1299   bool Invert = Pred == CmpInst::Predicate::ICMP_NE;
1300 
1301   // Emit a TB(N)Z.
1302   emitTestBit(TestReg, Bit, Invert, DstMBB, MIB);
1303   return true;
1304 }
1305 
1306 bool AArch64InstructionSelector::selectCompareBranch(
1307     MachineInstr &I, MachineFunction &MF, MachineRegisterInfo &MRI) const {
1308 
1309   const Register CondReg = I.getOperand(0).getReg();
1310   MachineBasicBlock *DestMBB = I.getOperand(1).getMBB();
1311   MachineInstr *CCMI = MRI.getVRegDef(CondReg);
1312   if (CCMI->getOpcode() == TargetOpcode::G_TRUNC)
1313     CCMI = MRI.getVRegDef(CCMI->getOperand(1).getReg());
1314 
1315   unsigned CCMIOpc = CCMI->getOpcode();
1316   if (CCMIOpc != TargetOpcode::G_ICMP && CCMIOpc != TargetOpcode::G_FCMP)
1317     return false;
1318 
1319   MachineIRBuilder MIB(I);
1320   Register LHS = CCMI->getOperand(2).getReg();
1321   Register RHS = CCMI->getOperand(3).getReg();
1322   auto Pred =
1323       static_cast<CmpInst::Predicate>(CCMI->getOperand(1).getPredicate());
1324 
1325   if (CCMIOpc == TargetOpcode::G_FCMP) {
1326     // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
1327     // totally clean.  Some of them require two branches to implement.
1328     emitFPCompare(LHS, RHS, MIB);
1329     AArch64CC::CondCode CC1, CC2;
1330     changeFCMPPredToAArch64CC(Pred, CC1, CC2);
1331     MIB.buildInstr(AArch64::Bcc, {}, {}).addImm(CC1).addMBB(DestMBB);
1332     if (CC2 != AArch64CC::AL)
1333       MIB.buildInstr(AArch64::Bcc, {}, {}).addImm(CC2).addMBB(DestMBB);
1334     I.eraseFromParent();
1335     return true;
1336   }
1337 
1338   auto VRegAndVal = getConstantVRegValWithLookThrough(RHS, MRI);
1339   MachineInstr *LHSMI = getDefIgnoringCopies(LHS, MRI);
1340 
1341   // When we can emit a TB(N)Z, prefer that.
1342   //
1343   // Handle non-commutative condition codes first.
1344   // Note that we don't want to do this when we have a G_AND because it can
1345   // become a tst. The tst will make the test bit in the TB(N)Z redundant.
1346   if (VRegAndVal && LHSMI->getOpcode() != TargetOpcode::G_AND) {
1347     int64_t C = VRegAndVal->Value;
1348 
1349     // When we have a greater-than comparison, we can just test if the msb is
1350     // zero.
1351     if (C == -1 && Pred == CmpInst::ICMP_SGT) {
1352       uint64_t Bit = MRI.getType(LHS).getSizeInBits() - 1;
1353       emitTestBit(LHS, Bit, /*IsNegative = */ false, DestMBB, MIB);
1354       I.eraseFromParent();
1355       return true;
1356     }
1357 
1358     // When we have a less than comparison, we can just test if the msb is not
1359     // zero.
1360     if (C == 0 && Pred == CmpInst::ICMP_SLT) {
1361       uint64_t Bit = MRI.getType(LHS).getSizeInBits() - 1;
1362       emitTestBit(LHS, Bit, /*IsNegative = */ true, DestMBB, MIB);
1363       I.eraseFromParent();
1364       return true;
1365     }
1366   }
1367 
1368   if (!VRegAndVal) {
1369     std::swap(RHS, LHS);
1370     VRegAndVal = getConstantVRegValWithLookThrough(RHS, MRI);
1371     LHSMI = getDefIgnoringCopies(LHS, MRI);
1372   }
1373 
1374   if (!VRegAndVal || VRegAndVal->Value != 0) {
1375     // If we can't select a CBZ then emit a cmp + Bcc.
1376     auto Pred =
1377         static_cast<CmpInst::Predicate>(CCMI->getOperand(1).getPredicate());
1378     emitIntegerCompare(CCMI->getOperand(2), CCMI->getOperand(3),
1379                        CCMI->getOperand(1), MIB);
1380     const AArch64CC::CondCode CC = changeICMPPredToAArch64CC(Pred);
1381     MIB.buildInstr(AArch64::Bcc, {}, {}).addImm(CC).addMBB(DestMBB);
1382     I.eraseFromParent();
1383     return true;
1384   }
1385 
1386   // Try to emit a TB(N)Z for an eq or ne condition.
1387   if (tryOptAndIntoCompareBranch(LHSMI, VRegAndVal->Value, Pred, DestMBB,
1388                                  MIB)) {
1389     I.eraseFromParent();
1390     return true;
1391   }
1392 
1393   const RegisterBank &RB = *RBI.getRegBank(LHS, MRI, TRI);
1394   if (RB.getID() != AArch64::GPRRegBankID)
1395     return false;
1396   if (Pred != CmpInst::ICMP_NE && Pred != CmpInst::ICMP_EQ)
1397     return false;
1398 
1399   const unsigned CmpWidth = MRI.getType(LHS).getSizeInBits();
1400   unsigned CBOpc = 0;
1401   if (CmpWidth <= 32)
1402     CBOpc = (Pred == CmpInst::ICMP_EQ ? AArch64::CBZW : AArch64::CBNZW);
1403   else if (CmpWidth == 64)
1404     CBOpc = (Pred == CmpInst::ICMP_EQ ? AArch64::CBZX : AArch64::CBNZX);
1405   else
1406     return false;
1407 
1408   BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(CBOpc))
1409       .addUse(LHS)
1410       .addMBB(DestMBB)
1411       .constrainAllUses(TII, TRI, RBI);
1412 
1413   I.eraseFromParent();
1414   return true;
1415 }
1416 
1417 /// Returns the element immediate value of a vector shift operand if found.
1418 /// This needs to detect a splat-like operation, e.g. a G_BUILD_VECTOR.
1419 static Optional<int64_t> getVectorShiftImm(Register Reg,
1420                                            MachineRegisterInfo &MRI) {
1421   assert(MRI.getType(Reg).isVector() && "Expected a *vector* shift operand");
1422   MachineInstr *OpMI = MRI.getVRegDef(Reg);
1423   assert(OpMI && "Expected to find a vreg def for vector shift operand");
1424   if (OpMI->getOpcode() != TargetOpcode::G_BUILD_VECTOR)
1425     return None;
1426 
1427   // Check all operands are identical immediates.
1428   int64_t ImmVal = 0;
1429   for (unsigned Idx = 1; Idx < OpMI->getNumOperands(); ++Idx) {
1430     auto VRegAndVal = getConstantVRegValWithLookThrough(OpMI->getOperand(Idx).getReg(), MRI);
1431     if (!VRegAndVal)
1432       return None;
1433 
1434     if (Idx == 1)
1435       ImmVal = VRegAndVal->Value;
1436     if (ImmVal != VRegAndVal->Value)
1437       return None;
1438   }
1439 
1440   return ImmVal;
1441 }
1442 
1443 /// Matches and returns the shift immediate value for a SHL instruction given
1444 /// a shift operand.
1445 static Optional<int64_t> getVectorSHLImm(LLT SrcTy, Register Reg, MachineRegisterInfo &MRI) {
1446   Optional<int64_t> ShiftImm = getVectorShiftImm(Reg, MRI);
1447   if (!ShiftImm)
1448     return None;
1449   // Check the immediate is in range for a SHL.
1450   int64_t Imm = *ShiftImm;
1451   if (Imm < 0)
1452     return None;
1453   switch (SrcTy.getElementType().getSizeInBits()) {
1454   default:
1455     LLVM_DEBUG(dbgs() << "Unhandled element type for vector shift");
1456     return None;
1457   case 8:
1458     if (Imm > 7)
1459       return None;
1460     break;
1461   case 16:
1462     if (Imm > 15)
1463       return None;
1464     break;
1465   case 32:
1466     if (Imm > 31)
1467       return None;
1468     break;
1469   case 64:
1470     if (Imm > 63)
1471       return None;
1472     break;
1473   }
1474   return Imm;
1475 }
1476 
1477 bool AArch64InstructionSelector::selectVectorSHL(
1478     MachineInstr &I, MachineRegisterInfo &MRI) const {
1479   assert(I.getOpcode() == TargetOpcode::G_SHL);
1480   Register DstReg = I.getOperand(0).getReg();
1481   const LLT Ty = MRI.getType(DstReg);
1482   Register Src1Reg = I.getOperand(1).getReg();
1483   Register Src2Reg = I.getOperand(2).getReg();
1484 
1485   if (!Ty.isVector())
1486     return false;
1487 
1488   // Check if we have a vector of constants on RHS that we can select as the
1489   // immediate form.
1490   Optional<int64_t> ImmVal = getVectorSHLImm(Ty, Src2Reg, MRI);
1491 
1492   unsigned Opc = 0;
1493   if (Ty == LLT::vector(2, 64)) {
1494     Opc = ImmVal ? AArch64::SHLv2i64_shift : AArch64::USHLv2i64;
1495   } else if (Ty == LLT::vector(4, 32)) {
1496     Opc = ImmVal ? AArch64::SHLv4i32_shift : AArch64::USHLv4i32;
1497   } else if (Ty == LLT::vector(2, 32)) {
1498     Opc = ImmVal ? AArch64::SHLv2i32_shift : AArch64::USHLv2i32;
1499   } else if (Ty == LLT::vector(4, 16)) {
1500     Opc = ImmVal ? AArch64::SHLv4i16_shift : AArch64::USHLv4i16;
1501   } else if (Ty == LLT::vector(8, 16)) {
1502     Opc = ImmVal ? AArch64::SHLv8i16_shift : AArch64::USHLv8i16;
1503   } else if (Ty == LLT::vector(16, 8)) {
1504     Opc = ImmVal ? AArch64::SHLv16i8_shift : AArch64::USHLv16i8;
1505   } else if (Ty == LLT::vector(8, 8)) {
1506     Opc = ImmVal ? AArch64::SHLv8i8_shift : AArch64::USHLv8i8;
1507   } else {
1508     LLVM_DEBUG(dbgs() << "Unhandled G_SHL type");
1509     return false;
1510   }
1511 
1512   MachineIRBuilder MIB(I);
1513   auto Shl = MIB.buildInstr(Opc, {DstReg}, {Src1Reg});
1514   if (ImmVal)
1515     Shl.addImm(*ImmVal);
1516   else
1517     Shl.addUse(Src2Reg);
1518   constrainSelectedInstRegOperands(*Shl, TII, TRI, RBI);
1519   I.eraseFromParent();
1520   return true;
1521 }
1522 
1523 bool AArch64InstructionSelector::selectVectorAshrLshr(
1524     MachineInstr &I, MachineRegisterInfo &MRI) const {
1525   assert(I.getOpcode() == TargetOpcode::G_ASHR ||
1526          I.getOpcode() == TargetOpcode::G_LSHR);
1527   Register DstReg = I.getOperand(0).getReg();
1528   const LLT Ty = MRI.getType(DstReg);
1529   Register Src1Reg = I.getOperand(1).getReg();
1530   Register Src2Reg = I.getOperand(2).getReg();
1531 
1532   if (!Ty.isVector())
1533     return false;
1534 
1535   bool IsASHR = I.getOpcode() == TargetOpcode::G_ASHR;
1536 
1537   // We expect the immediate case to be lowered in the PostLegalCombiner to
1538   // AArch64ISD::VASHR or AArch64ISD::VLSHR equivalents.
1539 
1540   // There is not a shift right register instruction, but the shift left
1541   // register instruction takes a signed value, where negative numbers specify a
1542   // right shift.
1543 
1544   unsigned Opc = 0;
1545   unsigned NegOpc = 0;
1546   const TargetRegisterClass *RC =
1547       getRegClassForTypeOnBank(Ty, RBI.getRegBank(AArch64::FPRRegBankID), RBI);
1548   if (Ty == LLT::vector(2, 64)) {
1549     Opc = IsASHR ? AArch64::SSHLv2i64 : AArch64::USHLv2i64;
1550     NegOpc = AArch64::NEGv2i64;
1551   } else if (Ty == LLT::vector(4, 32)) {
1552     Opc = IsASHR ? AArch64::SSHLv4i32 : AArch64::USHLv4i32;
1553     NegOpc = AArch64::NEGv4i32;
1554   } else if (Ty == LLT::vector(2, 32)) {
1555     Opc = IsASHR ? AArch64::SSHLv2i32 : AArch64::USHLv2i32;
1556     NegOpc = AArch64::NEGv2i32;
1557   } else if (Ty == LLT::vector(4, 16)) {
1558     Opc = IsASHR ? AArch64::SSHLv4i16 : AArch64::USHLv4i16;
1559     NegOpc = AArch64::NEGv4i16;
1560   } else if (Ty == LLT::vector(8, 16)) {
1561     Opc = IsASHR ? AArch64::SSHLv8i16 : AArch64::USHLv8i16;
1562     NegOpc = AArch64::NEGv8i16;
1563   } else if (Ty == LLT::vector(16, 8)) {
1564     Opc = IsASHR ? AArch64::SSHLv16i8 : AArch64::USHLv16i8;
1565     NegOpc = AArch64::NEGv8i16;
1566   } else if (Ty == LLT::vector(8, 8)) {
1567     Opc = IsASHR ? AArch64::SSHLv8i8 : AArch64::USHLv8i8;
1568     NegOpc = AArch64::NEGv8i8;
1569   } else {
1570     LLVM_DEBUG(dbgs() << "Unhandled G_ASHR type");
1571     return false;
1572   }
1573 
1574   MachineIRBuilder MIB(I);
1575   auto Neg = MIB.buildInstr(NegOpc, {RC}, {Src2Reg});
1576   constrainSelectedInstRegOperands(*Neg, TII, TRI, RBI);
1577   auto SShl = MIB.buildInstr(Opc, {DstReg}, {Src1Reg, Neg});
1578   constrainSelectedInstRegOperands(*SShl, TII, TRI, RBI);
1579   I.eraseFromParent();
1580   return true;
1581 }
1582 
1583 bool AArch64InstructionSelector::selectVaStartAAPCS(
1584     MachineInstr &I, MachineFunction &MF, MachineRegisterInfo &MRI) const {
1585   return false;
1586 }
1587 
1588 bool AArch64InstructionSelector::selectVaStartDarwin(
1589     MachineInstr &I, MachineFunction &MF, MachineRegisterInfo &MRI) const {
1590   AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
1591   Register ListReg = I.getOperand(0).getReg();
1592 
1593   Register ArgsAddrReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
1594 
1595   auto MIB =
1596       BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(AArch64::ADDXri))
1597           .addDef(ArgsAddrReg)
1598           .addFrameIndex(FuncInfo->getVarArgsStackIndex())
1599           .addImm(0)
1600           .addImm(0);
1601 
1602   constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
1603 
1604   MIB = BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(AArch64::STRXui))
1605             .addUse(ArgsAddrReg)
1606             .addUse(ListReg)
1607             .addImm(0)
1608             .addMemOperand(*I.memoperands_begin());
1609 
1610   constrainSelectedInstRegOperands(*MIB, TII, TRI, RBI);
1611   I.eraseFromParent();
1612   return true;
1613 }
1614 
1615 void AArch64InstructionSelector::materializeLargeCMVal(
1616     MachineInstr &I, const Value *V, unsigned OpFlags) const {
1617   MachineBasicBlock &MBB = *I.getParent();
1618   MachineFunction &MF = *MBB.getParent();
1619   MachineRegisterInfo &MRI = MF.getRegInfo();
1620   MachineIRBuilder MIB(I);
1621 
1622   auto MovZ = MIB.buildInstr(AArch64::MOVZXi, {&AArch64::GPR64RegClass}, {});
1623   MovZ->addOperand(MF, I.getOperand(1));
1624   MovZ->getOperand(1).setTargetFlags(OpFlags | AArch64II::MO_G0 |
1625                                      AArch64II::MO_NC);
1626   MovZ->addOperand(MF, MachineOperand::CreateImm(0));
1627   constrainSelectedInstRegOperands(*MovZ, TII, TRI, RBI);
1628 
1629   auto BuildMovK = [&](Register SrcReg, unsigned char Flags, unsigned Offset,
1630                        Register ForceDstReg) {
1631     Register DstReg = ForceDstReg
1632                           ? ForceDstReg
1633                           : MRI.createVirtualRegister(&AArch64::GPR64RegClass);
1634     auto MovI = MIB.buildInstr(AArch64::MOVKXi).addDef(DstReg).addUse(SrcReg);
1635     if (auto *GV = dyn_cast<GlobalValue>(V)) {
1636       MovI->addOperand(MF, MachineOperand::CreateGA(
1637                                GV, MovZ->getOperand(1).getOffset(), Flags));
1638     } else {
1639       MovI->addOperand(
1640           MF, MachineOperand::CreateBA(cast<BlockAddress>(V),
1641                                        MovZ->getOperand(1).getOffset(), Flags));
1642     }
1643     MovI->addOperand(MF, MachineOperand::CreateImm(Offset));
1644     constrainSelectedInstRegOperands(*MovI, TII, TRI, RBI);
1645     return DstReg;
1646   };
1647   Register DstReg = BuildMovK(MovZ.getReg(0),
1648                               AArch64II::MO_G1 | AArch64II::MO_NC, 16, 0);
1649   DstReg = BuildMovK(DstReg, AArch64II::MO_G2 | AArch64II::MO_NC, 32, 0);
1650   BuildMovK(DstReg, AArch64II::MO_G3, 48, I.getOperand(0).getReg());
1651   return;
1652 }
1653 
1654 bool AArch64InstructionSelector::preISelLower(MachineInstr &I) {
1655   MachineBasicBlock &MBB = *I.getParent();
1656   MachineFunction &MF = *MBB.getParent();
1657   MachineRegisterInfo &MRI = MF.getRegInfo();
1658 
1659   switch (I.getOpcode()) {
1660   case TargetOpcode::G_SHL:
1661   case TargetOpcode::G_ASHR:
1662   case TargetOpcode::G_LSHR: {
1663     // These shifts are legalized to have 64 bit shift amounts because we want
1664     // to take advantage of the existing imported selection patterns that assume
1665     // the immediates are s64s. However, if the shifted type is 32 bits and for
1666     // some reason we receive input GMIR that has an s64 shift amount that's not
1667     // a G_CONSTANT, insert a truncate so that we can still select the s32
1668     // register-register variant.
1669     Register SrcReg = I.getOperand(1).getReg();
1670     Register ShiftReg = I.getOperand(2).getReg();
1671     const LLT ShiftTy = MRI.getType(ShiftReg);
1672     const LLT SrcTy = MRI.getType(SrcReg);
1673     if (SrcTy.isVector())
1674       return false;
1675     assert(!ShiftTy.isVector() && "unexpected vector shift ty");
1676     if (SrcTy.getSizeInBits() != 32 || ShiftTy.getSizeInBits() != 64)
1677       return false;
1678     auto *AmtMI = MRI.getVRegDef(ShiftReg);
1679     assert(AmtMI && "could not find a vreg definition for shift amount");
1680     if (AmtMI->getOpcode() != TargetOpcode::G_CONSTANT) {
1681       // Insert a subregister copy to implement a 64->32 trunc
1682       MachineIRBuilder MIB(I);
1683       auto Trunc = MIB.buildInstr(TargetOpcode::COPY, {SrcTy}, {})
1684                        .addReg(ShiftReg, 0, AArch64::sub_32);
1685       MRI.setRegBank(Trunc.getReg(0), RBI.getRegBank(AArch64::GPRRegBankID));
1686       I.getOperand(2).setReg(Trunc.getReg(0));
1687     }
1688     return true;
1689   }
1690   case TargetOpcode::G_STORE:
1691     return contractCrossBankCopyIntoStore(I, MRI);
1692   case TargetOpcode::G_PTR_ADD:
1693     return convertPtrAddToAdd(I, MRI);
1694   case TargetOpcode::G_LOAD: {
1695     // For scalar loads of pointers, we try to convert the dest type from p0
1696     // to s64 so that our imported patterns can match. Like with the G_PTR_ADD
1697     // conversion, this should be ok because all users should have been
1698     // selected already, so the type doesn't matter for them.
1699     Register DstReg = I.getOperand(0).getReg();
1700     const LLT DstTy = MRI.getType(DstReg);
1701     if (!DstTy.isPointer())
1702       return false;
1703     MRI.setType(DstReg, LLT::scalar(64));
1704     return true;
1705   }
1706   default:
1707     return false;
1708   }
1709 }
1710 
1711 /// This lowering tries to look for G_PTR_ADD instructions and then converts
1712 /// them to a standard G_ADD with a COPY on the source.
1713 ///
1714 /// The motivation behind this is to expose the add semantics to the imported
1715 /// tablegen patterns. We shouldn't need to check for uses being loads/stores,
1716 /// because the selector works bottom up, uses before defs. By the time we
1717 /// end up trying to select a G_PTR_ADD, we should have already attempted to
1718 /// fold this into addressing modes and were therefore unsuccessful.
1719 bool AArch64InstructionSelector::convertPtrAddToAdd(
1720     MachineInstr &I, MachineRegisterInfo &MRI) {
1721   assert(I.getOpcode() == TargetOpcode::G_PTR_ADD && "Expected G_PTR_ADD");
1722   Register DstReg = I.getOperand(0).getReg();
1723   Register AddOp1Reg = I.getOperand(1).getReg();
1724   const LLT PtrTy = MRI.getType(DstReg);
1725   if (PtrTy.getAddressSpace() != 0)
1726     return false;
1727 
1728   MachineIRBuilder MIB(I);
1729   const LLT CastPtrTy = PtrTy.isVector() ? LLT::vector(2, 64) : LLT::scalar(64);
1730   auto PtrToInt = MIB.buildPtrToInt(CastPtrTy, AddOp1Reg);
1731   // Set regbanks on the registers.
1732   if (PtrTy.isVector())
1733     MRI.setRegBank(PtrToInt.getReg(0), RBI.getRegBank(AArch64::FPRRegBankID));
1734   else
1735     MRI.setRegBank(PtrToInt.getReg(0), RBI.getRegBank(AArch64::GPRRegBankID));
1736 
1737   // Now turn the %dst(p0) = G_PTR_ADD %base, off into:
1738   // %dst(intty) = G_ADD %intbase, off
1739   I.setDesc(TII.get(TargetOpcode::G_ADD));
1740   MRI.setType(DstReg, CastPtrTy);
1741   I.getOperand(1).setReg(PtrToInt.getReg(0));
1742   if (!select(*PtrToInt)) {
1743     LLVM_DEBUG(dbgs() << "Failed to select G_PTRTOINT in convertPtrAddToAdd");
1744     return false;
1745   }
1746   return true;
1747 }
1748 
1749 bool AArch64InstructionSelector::earlySelectSHL(
1750     MachineInstr &I, MachineRegisterInfo &MRI) const {
1751   // We try to match the immediate variant of LSL, which is actually an alias
1752   // for a special case of UBFM. Otherwise, we fall back to the imported
1753   // selector which will match the register variant.
1754   assert(I.getOpcode() == TargetOpcode::G_SHL && "unexpected op");
1755   const auto &MO = I.getOperand(2);
1756   auto VRegAndVal = getConstantVRegVal(MO.getReg(), MRI);
1757   if (!VRegAndVal)
1758     return false;
1759 
1760   const LLT DstTy = MRI.getType(I.getOperand(0).getReg());
1761   if (DstTy.isVector())
1762     return false;
1763   bool Is64Bit = DstTy.getSizeInBits() == 64;
1764   auto Imm1Fn = Is64Bit ? selectShiftA_64(MO) : selectShiftA_32(MO);
1765   auto Imm2Fn = Is64Bit ? selectShiftB_64(MO) : selectShiftB_32(MO);
1766   MachineIRBuilder MIB(I);
1767 
1768   if (!Imm1Fn || !Imm2Fn)
1769     return false;
1770 
1771   auto NewI =
1772       MIB.buildInstr(Is64Bit ? AArch64::UBFMXri : AArch64::UBFMWri,
1773                      {I.getOperand(0).getReg()}, {I.getOperand(1).getReg()});
1774 
1775   for (auto &RenderFn : *Imm1Fn)
1776     RenderFn(NewI);
1777   for (auto &RenderFn : *Imm2Fn)
1778     RenderFn(NewI);
1779 
1780   I.eraseFromParent();
1781   return constrainSelectedInstRegOperands(*NewI, TII, TRI, RBI);
1782 }
1783 
1784 bool AArch64InstructionSelector::contractCrossBankCopyIntoStore(
1785     MachineInstr &I, MachineRegisterInfo &MRI) {
1786   assert(I.getOpcode() == TargetOpcode::G_STORE && "Expected G_STORE");
1787   // If we're storing a scalar, it doesn't matter what register bank that
1788   // scalar is on. All that matters is the size.
1789   //
1790   // So, if we see something like this (with a 32-bit scalar as an example):
1791   //
1792   // %x:gpr(s32) = ... something ...
1793   // %y:fpr(s32) = COPY %x:gpr(s32)
1794   // G_STORE %y:fpr(s32)
1795   //
1796   // We can fix this up into something like this:
1797   //
1798   // G_STORE %x:gpr(s32)
1799   //
1800   // And then continue the selection process normally.
1801   Register DefDstReg = getSrcRegIgnoringCopies(I.getOperand(0).getReg(), MRI);
1802   if (!DefDstReg.isValid())
1803     return false;
1804   LLT DefDstTy = MRI.getType(DefDstReg);
1805   Register StoreSrcReg = I.getOperand(0).getReg();
1806   LLT StoreSrcTy = MRI.getType(StoreSrcReg);
1807 
1808   // If we get something strange like a physical register, then we shouldn't
1809   // go any further.
1810   if (!DefDstTy.isValid())
1811     return false;
1812 
1813   // Are the source and dst types the same size?
1814   if (DefDstTy.getSizeInBits() != StoreSrcTy.getSizeInBits())
1815     return false;
1816 
1817   if (RBI.getRegBank(StoreSrcReg, MRI, TRI) ==
1818       RBI.getRegBank(DefDstReg, MRI, TRI))
1819     return false;
1820 
1821   // We have a cross-bank copy, which is entering a store. Let's fold it.
1822   I.getOperand(0).setReg(DefDstReg);
1823   return true;
1824 }
1825 
1826 bool AArch64InstructionSelector::earlySelect(MachineInstr &I) const {
1827   assert(I.getParent() && "Instruction should be in a basic block!");
1828   assert(I.getParent()->getParent() && "Instruction should be in a function!");
1829 
1830   MachineBasicBlock &MBB = *I.getParent();
1831   MachineFunction &MF = *MBB.getParent();
1832   MachineRegisterInfo &MRI = MF.getRegInfo();
1833 
1834   switch (I.getOpcode()) {
1835   case TargetOpcode::G_BR: {
1836     // If the branch jumps to the fallthrough block, don't bother emitting it.
1837     // Only do this for -O0 for a good code size improvement, because when
1838     // optimizations are enabled we want to leave this choice to
1839     // MachineBlockPlacement.
1840     bool EnableOpt = MF.getTarget().getOptLevel() != CodeGenOpt::None;
1841     if (EnableOpt || !MBB.isLayoutSuccessor(I.getOperand(0).getMBB()))
1842       return false;
1843     I.eraseFromParent();
1844     return true;
1845   }
1846   case TargetOpcode::G_SHL:
1847     return earlySelectSHL(I, MRI);
1848   case TargetOpcode::G_CONSTANT: {
1849     bool IsZero = false;
1850     if (I.getOperand(1).isCImm())
1851       IsZero = I.getOperand(1).getCImm()->getZExtValue() == 0;
1852     else if (I.getOperand(1).isImm())
1853       IsZero = I.getOperand(1).getImm() == 0;
1854 
1855     if (!IsZero)
1856       return false;
1857 
1858     Register DefReg = I.getOperand(0).getReg();
1859     LLT Ty = MRI.getType(DefReg);
1860     if (Ty.getSizeInBits() == 64) {
1861       I.getOperand(1).ChangeToRegister(AArch64::XZR, false);
1862       RBI.constrainGenericRegister(DefReg, AArch64::GPR64RegClass, MRI);
1863     } else if (Ty.getSizeInBits() == 32) {
1864       I.getOperand(1).ChangeToRegister(AArch64::WZR, false);
1865       RBI.constrainGenericRegister(DefReg, AArch64::GPR32RegClass, MRI);
1866     } else
1867       return false;
1868 
1869     I.setDesc(TII.get(TargetOpcode::COPY));
1870     return true;
1871   }
1872   default:
1873     return false;
1874   }
1875 }
1876 
1877 bool AArch64InstructionSelector::select(MachineInstr &I) {
1878   assert(I.getParent() && "Instruction should be in a basic block!");
1879   assert(I.getParent()->getParent() && "Instruction should be in a function!");
1880 
1881   MachineBasicBlock &MBB = *I.getParent();
1882   MachineFunction &MF = *MBB.getParent();
1883   MachineRegisterInfo &MRI = MF.getRegInfo();
1884 
1885   const AArch64Subtarget *Subtarget =
1886       &static_cast<const AArch64Subtarget &>(MF.getSubtarget());
1887   if (Subtarget->requiresStrictAlign()) {
1888     // We don't support this feature yet.
1889     LLVM_DEBUG(dbgs() << "AArch64 GISel does not support strict-align yet\n");
1890     return false;
1891   }
1892 
1893   unsigned Opcode = I.getOpcode();
1894   // G_PHI requires same handling as PHI
1895   if (!I.isPreISelOpcode() || Opcode == TargetOpcode::G_PHI) {
1896     // Certain non-generic instructions also need some special handling.
1897 
1898     if (Opcode ==  TargetOpcode::LOAD_STACK_GUARD)
1899       return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
1900 
1901     if (Opcode == TargetOpcode::PHI || Opcode == TargetOpcode::G_PHI) {
1902       const Register DefReg = I.getOperand(0).getReg();
1903       const LLT DefTy = MRI.getType(DefReg);
1904 
1905       const RegClassOrRegBank &RegClassOrBank =
1906         MRI.getRegClassOrRegBank(DefReg);
1907 
1908       const TargetRegisterClass *DefRC
1909         = RegClassOrBank.dyn_cast<const TargetRegisterClass *>();
1910       if (!DefRC) {
1911         if (!DefTy.isValid()) {
1912           LLVM_DEBUG(dbgs() << "PHI operand has no type, not a gvreg?\n");
1913           return false;
1914         }
1915         const RegisterBank &RB = *RegClassOrBank.get<const RegisterBank *>();
1916         DefRC = getRegClassForTypeOnBank(DefTy, RB, RBI);
1917         if (!DefRC) {
1918           LLVM_DEBUG(dbgs() << "PHI operand has unexpected size/bank\n");
1919           return false;
1920         }
1921       }
1922 
1923       I.setDesc(TII.get(TargetOpcode::PHI));
1924 
1925       return RBI.constrainGenericRegister(DefReg, *DefRC, MRI);
1926     }
1927 
1928     if (I.isCopy())
1929       return selectCopy(I, TII, MRI, TRI, RBI);
1930 
1931     return true;
1932   }
1933 
1934 
1935   if (I.getNumOperands() != I.getNumExplicitOperands()) {
1936     LLVM_DEBUG(
1937         dbgs() << "Generic instruction has unexpected implicit operands\n");
1938     return false;
1939   }
1940 
1941   // Try to do some lowering before we start instruction selecting. These
1942   // lowerings are purely transformations on the input G_MIR and so selection
1943   // must continue after any modification of the instruction.
1944   if (preISelLower(I)) {
1945     Opcode = I.getOpcode(); // The opcode may have been modified, refresh it.
1946   }
1947 
1948   // There may be patterns where the importer can't deal with them optimally,
1949   // but does select it to a suboptimal sequence so our custom C++ selection
1950   // code later never has a chance to work on it. Therefore, we have an early
1951   // selection attempt here to give priority to certain selection routines
1952   // over the imported ones.
1953   if (earlySelect(I))
1954     return true;
1955 
1956   if (selectImpl(I, *CoverageInfo))
1957     return true;
1958 
1959   LLT Ty =
1960       I.getOperand(0).isReg() ? MRI.getType(I.getOperand(0).getReg()) : LLT{};
1961 
1962   MachineIRBuilder MIB(I);
1963 
1964   switch (Opcode) {
1965   case TargetOpcode::G_BRCOND: {
1966     Register CondReg = I.getOperand(0).getReg();
1967     MachineBasicBlock *DestMBB = I.getOperand(1).getMBB();
1968 
1969     // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z
1970     // instructions will not be produced, as they are conditional branch
1971     // instructions that do not set flags.
1972     if (ProduceNonFlagSettingCondBr && selectCompareBranch(I, MF, MRI))
1973       return true;
1974 
1975     if (ProduceNonFlagSettingCondBr) {
1976       auto TestBit = emitTestBit(CondReg, /*Bit = */ 0, /*IsNegative = */ true,
1977                                  DestMBB, MIB);
1978       I.eraseFromParent();
1979       return constrainSelectedInstRegOperands(*TestBit, TII, TRI, RBI);
1980     } else {
1981       auto CMP = BuildMI(MBB, I, I.getDebugLoc(), TII.get(AArch64::ANDSWri))
1982                      .addDef(AArch64::WZR)
1983                      .addUse(CondReg)
1984                      .addImm(1);
1985       constrainSelectedInstRegOperands(*CMP.getInstr(), TII, TRI, RBI);
1986       auto Bcc =
1987           BuildMI(MBB, I, I.getDebugLoc(), TII.get(AArch64::Bcc))
1988               .addImm(AArch64CC::EQ)
1989               .addMBB(DestMBB);
1990 
1991       I.eraseFromParent();
1992       return constrainSelectedInstRegOperands(*Bcc.getInstr(), TII, TRI, RBI);
1993     }
1994   }
1995 
1996   case TargetOpcode::G_BRINDIRECT: {
1997     I.setDesc(TII.get(AArch64::BR));
1998     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
1999   }
2000 
2001   case TargetOpcode::G_BRJT:
2002     return selectBrJT(I, MRI);
2003 
2004   case AArch64::G_ADD_LOW: {
2005     // This op may have been separated from it's ADRP companion by the localizer
2006     // or some other code motion pass. Given that many CPUs will try to
2007     // macro fuse these operations anyway, select this into a MOVaddr pseudo
2008     // which will later be expanded into an ADRP+ADD pair after scheduling.
2009     MachineInstr *BaseMI = MRI.getVRegDef(I.getOperand(1).getReg());
2010     if (BaseMI->getOpcode() != AArch64::ADRP) {
2011       I.setDesc(TII.get(AArch64::ADDXri));
2012       I.addOperand(MachineOperand::CreateImm(0));
2013       return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2014     }
2015     assert(TM.getCodeModel() == CodeModel::Small &&
2016            "Expected small code model");
2017     MachineIRBuilder MIB(I);
2018     auto Op1 = BaseMI->getOperand(1);
2019     auto Op2 = I.getOperand(2);
2020     auto MovAddr = MIB.buildInstr(AArch64::MOVaddr, {I.getOperand(0)}, {})
2021                        .addGlobalAddress(Op1.getGlobal(), Op1.getOffset(),
2022                                          Op1.getTargetFlags())
2023                        .addGlobalAddress(Op2.getGlobal(), Op2.getOffset(),
2024                                          Op2.getTargetFlags());
2025     I.eraseFromParent();
2026     return constrainSelectedInstRegOperands(*MovAddr, TII, TRI, RBI);
2027   }
2028 
2029   case TargetOpcode::G_BSWAP: {
2030     // Handle vector types for G_BSWAP directly.
2031     Register DstReg = I.getOperand(0).getReg();
2032     LLT DstTy = MRI.getType(DstReg);
2033 
2034     // We should only get vector types here; everything else is handled by the
2035     // importer right now.
2036     if (!DstTy.isVector() || DstTy.getSizeInBits() > 128) {
2037       LLVM_DEBUG(dbgs() << "Dst type for G_BSWAP currently unsupported.\n");
2038       return false;
2039     }
2040 
2041     // Only handle 4 and 2 element vectors for now.
2042     // TODO: 16-bit elements.
2043     unsigned NumElts = DstTy.getNumElements();
2044     if (NumElts != 4 && NumElts != 2) {
2045       LLVM_DEBUG(dbgs() << "Unsupported number of elements for G_BSWAP.\n");
2046       return false;
2047     }
2048 
2049     // Choose the correct opcode for the supported types. Right now, that's
2050     // v2s32, v4s32, and v2s64.
2051     unsigned Opc = 0;
2052     unsigned EltSize = DstTy.getElementType().getSizeInBits();
2053     if (EltSize == 32)
2054       Opc = (DstTy.getNumElements() == 2) ? AArch64::REV32v8i8
2055                                           : AArch64::REV32v16i8;
2056     else if (EltSize == 64)
2057       Opc = AArch64::REV64v16i8;
2058 
2059     // We should always get something by the time we get here...
2060     assert(Opc != 0 && "Didn't get an opcode for G_BSWAP?");
2061 
2062     I.setDesc(TII.get(Opc));
2063     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2064   }
2065 
2066   case TargetOpcode::G_FCONSTANT:
2067   case TargetOpcode::G_CONSTANT: {
2068     const bool isFP = Opcode == TargetOpcode::G_FCONSTANT;
2069 
2070     const LLT s8 = LLT::scalar(8);
2071     const LLT s16 = LLT::scalar(16);
2072     const LLT s32 = LLT::scalar(32);
2073     const LLT s64 = LLT::scalar(64);
2074     const LLT p0 = LLT::pointer(0, 64);
2075 
2076     const Register DefReg = I.getOperand(0).getReg();
2077     const LLT DefTy = MRI.getType(DefReg);
2078     const unsigned DefSize = DefTy.getSizeInBits();
2079     const RegisterBank &RB = *RBI.getRegBank(DefReg, MRI, TRI);
2080 
2081     // FIXME: Redundant check, but even less readable when factored out.
2082     if (isFP) {
2083       if (Ty != s32 && Ty != s64) {
2084         LLVM_DEBUG(dbgs() << "Unable to materialize FP " << Ty
2085                           << " constant, expected: " << s32 << " or " << s64
2086                           << '\n');
2087         return false;
2088       }
2089 
2090       if (RB.getID() != AArch64::FPRRegBankID) {
2091         LLVM_DEBUG(dbgs() << "Unable to materialize FP " << Ty
2092                           << " constant on bank: " << RB
2093                           << ", expected: FPR\n");
2094         return false;
2095       }
2096 
2097       // The case when we have 0.0 is covered by tablegen. Reject it here so we
2098       // can be sure tablegen works correctly and isn't rescued by this code.
2099       if (I.getOperand(1).getFPImm()->getValueAPF().isExactlyValue(0.0))
2100         return false;
2101     } else {
2102       // s32 and s64 are covered by tablegen.
2103       if (Ty != p0 && Ty != s8 && Ty != s16) {
2104         LLVM_DEBUG(dbgs() << "Unable to materialize integer " << Ty
2105                           << " constant, expected: " << s32 << ", " << s64
2106                           << ", or " << p0 << '\n');
2107         return false;
2108       }
2109 
2110       if (RB.getID() != AArch64::GPRRegBankID) {
2111         LLVM_DEBUG(dbgs() << "Unable to materialize integer " << Ty
2112                           << " constant on bank: " << RB
2113                           << ", expected: GPR\n");
2114         return false;
2115       }
2116     }
2117 
2118     // We allow G_CONSTANT of types < 32b.
2119     const unsigned MovOpc =
2120         DefSize == 64 ? AArch64::MOVi64imm : AArch64::MOVi32imm;
2121 
2122     if (isFP) {
2123       // Either emit a FMOV, or emit a copy to emit a normal mov.
2124       const TargetRegisterClass &GPRRC =
2125           DefSize == 32 ? AArch64::GPR32RegClass : AArch64::GPR64RegClass;
2126       const TargetRegisterClass &FPRRC =
2127           DefSize == 32 ? AArch64::FPR32RegClass : AArch64::FPR64RegClass;
2128 
2129       // Can we use a FMOV instruction to represent the immediate?
2130       if (emitFMovForFConstant(I, MRI))
2131         return true;
2132 
2133       // For 64b values, emit a constant pool load instead.
2134       if (DefSize == 64) {
2135         auto *FPImm = I.getOperand(1).getFPImm();
2136         MachineIRBuilder MIB(I);
2137         auto *LoadMI = emitLoadFromConstantPool(FPImm, MIB);
2138         if (!LoadMI) {
2139           LLVM_DEBUG(dbgs() << "Failed to load double constant pool entry\n");
2140           return false;
2141         }
2142         MIB.buildCopy({DefReg}, {LoadMI->getOperand(0).getReg()});
2143         I.eraseFromParent();
2144         return RBI.constrainGenericRegister(DefReg, FPRRC, MRI);
2145       }
2146 
2147       // Nope. Emit a copy and use a normal mov instead.
2148       const Register DefGPRReg = MRI.createVirtualRegister(&GPRRC);
2149       MachineOperand &RegOp = I.getOperand(0);
2150       RegOp.setReg(DefGPRReg);
2151       MIB.setInsertPt(MIB.getMBB(), std::next(I.getIterator()));
2152       MIB.buildCopy({DefReg}, {DefGPRReg});
2153 
2154       if (!RBI.constrainGenericRegister(DefReg, FPRRC, MRI)) {
2155         LLVM_DEBUG(dbgs() << "Failed to constrain G_FCONSTANT def operand\n");
2156         return false;
2157       }
2158 
2159       MachineOperand &ImmOp = I.getOperand(1);
2160       // FIXME: Is going through int64_t always correct?
2161       ImmOp.ChangeToImmediate(
2162           ImmOp.getFPImm()->getValueAPF().bitcastToAPInt().getZExtValue());
2163     } else if (I.getOperand(1).isCImm()) {
2164       uint64_t Val = I.getOperand(1).getCImm()->getZExtValue();
2165       I.getOperand(1).ChangeToImmediate(Val);
2166     } else if (I.getOperand(1).isImm()) {
2167       uint64_t Val = I.getOperand(1).getImm();
2168       I.getOperand(1).ChangeToImmediate(Val);
2169     }
2170 
2171     I.setDesc(TII.get(MovOpc));
2172     constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2173     return true;
2174   }
2175   case TargetOpcode::G_EXTRACT: {
2176     Register DstReg = I.getOperand(0).getReg();
2177     Register SrcReg = I.getOperand(1).getReg();
2178     LLT SrcTy = MRI.getType(SrcReg);
2179     LLT DstTy = MRI.getType(DstReg);
2180     (void)DstTy;
2181     unsigned SrcSize = SrcTy.getSizeInBits();
2182 
2183     if (SrcTy.getSizeInBits() > 64) {
2184       // This should be an extract of an s128, which is like a vector extract.
2185       if (SrcTy.getSizeInBits() != 128)
2186         return false;
2187       // Only support extracting 64 bits from an s128 at the moment.
2188       if (DstTy.getSizeInBits() != 64)
2189         return false;
2190 
2191       const RegisterBank &SrcRB = *RBI.getRegBank(SrcReg, MRI, TRI);
2192       const RegisterBank &DstRB = *RBI.getRegBank(DstReg, MRI, TRI);
2193       // Check we have the right regbank always.
2194       assert(SrcRB.getID() == AArch64::FPRRegBankID &&
2195              DstRB.getID() == AArch64::FPRRegBankID &&
2196              "Wrong extract regbank!");
2197       (void)SrcRB;
2198 
2199       // Emit the same code as a vector extract.
2200       // Offset must be a multiple of 64.
2201       unsigned Offset = I.getOperand(2).getImm();
2202       if (Offset % 64 != 0)
2203         return false;
2204       unsigned LaneIdx = Offset / 64;
2205       MachineIRBuilder MIB(I);
2206       MachineInstr *Extract = emitExtractVectorElt(
2207           DstReg, DstRB, LLT::scalar(64), SrcReg, LaneIdx, MIB);
2208       if (!Extract)
2209         return false;
2210       I.eraseFromParent();
2211       return true;
2212     }
2213 
2214     I.setDesc(TII.get(SrcSize == 64 ? AArch64::UBFMXri : AArch64::UBFMWri));
2215     MachineInstrBuilder(MF, I).addImm(I.getOperand(2).getImm() +
2216                                       Ty.getSizeInBits() - 1);
2217 
2218     if (SrcSize < 64) {
2219       assert(SrcSize == 32 && DstTy.getSizeInBits() == 16 &&
2220              "unexpected G_EXTRACT types");
2221       return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2222     }
2223 
2224     DstReg = MRI.createGenericVirtualRegister(LLT::scalar(64));
2225     MIB.setInsertPt(MIB.getMBB(), std::next(I.getIterator()));
2226     MIB.buildInstr(TargetOpcode::COPY, {I.getOperand(0).getReg()}, {})
2227         .addReg(DstReg, 0, AArch64::sub_32);
2228     RBI.constrainGenericRegister(I.getOperand(0).getReg(),
2229                                  AArch64::GPR32RegClass, MRI);
2230     I.getOperand(0).setReg(DstReg);
2231 
2232     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2233   }
2234 
2235   case TargetOpcode::G_INSERT: {
2236     LLT SrcTy = MRI.getType(I.getOperand(2).getReg());
2237     LLT DstTy = MRI.getType(I.getOperand(0).getReg());
2238     unsigned DstSize = DstTy.getSizeInBits();
2239     // Larger inserts are vectors, same-size ones should be something else by
2240     // now (split up or turned into COPYs).
2241     if (Ty.getSizeInBits() > 64 || SrcTy.getSizeInBits() > 32)
2242       return false;
2243 
2244     I.setDesc(TII.get(DstSize == 64 ? AArch64::BFMXri : AArch64::BFMWri));
2245     unsigned LSB = I.getOperand(3).getImm();
2246     unsigned Width = MRI.getType(I.getOperand(2).getReg()).getSizeInBits();
2247     I.getOperand(3).setImm((DstSize - LSB) % DstSize);
2248     MachineInstrBuilder(MF, I).addImm(Width - 1);
2249 
2250     if (DstSize < 64) {
2251       assert(DstSize == 32 && SrcTy.getSizeInBits() == 16 &&
2252              "unexpected G_INSERT types");
2253       return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2254     }
2255 
2256     Register SrcReg = MRI.createGenericVirtualRegister(LLT::scalar(64));
2257     BuildMI(MBB, I.getIterator(), I.getDebugLoc(),
2258             TII.get(AArch64::SUBREG_TO_REG))
2259         .addDef(SrcReg)
2260         .addImm(0)
2261         .addUse(I.getOperand(2).getReg())
2262         .addImm(AArch64::sub_32);
2263     RBI.constrainGenericRegister(I.getOperand(2).getReg(),
2264                                  AArch64::GPR32RegClass, MRI);
2265     I.getOperand(2).setReg(SrcReg);
2266 
2267     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2268   }
2269   case TargetOpcode::G_FRAME_INDEX: {
2270     // allocas and G_FRAME_INDEX are only supported in addrspace(0).
2271     if (Ty != LLT::pointer(0, 64)) {
2272       LLVM_DEBUG(dbgs() << "G_FRAME_INDEX pointer has type: " << Ty
2273                         << ", expected: " << LLT::pointer(0, 64) << '\n');
2274       return false;
2275     }
2276     I.setDesc(TII.get(AArch64::ADDXri));
2277 
2278     // MOs for a #0 shifted immediate.
2279     I.addOperand(MachineOperand::CreateImm(0));
2280     I.addOperand(MachineOperand::CreateImm(0));
2281 
2282     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2283   }
2284 
2285   case TargetOpcode::G_GLOBAL_VALUE: {
2286     auto GV = I.getOperand(1).getGlobal();
2287     if (GV->isThreadLocal())
2288       return selectTLSGlobalValue(I, MRI);
2289 
2290     unsigned OpFlags = STI.ClassifyGlobalReference(GV, TM);
2291     if (OpFlags & AArch64II::MO_GOT) {
2292       I.setDesc(TII.get(AArch64::LOADgot));
2293       I.getOperand(1).setTargetFlags(OpFlags);
2294     } else if (TM.getCodeModel() == CodeModel::Large) {
2295       // Materialize the global using movz/movk instructions.
2296       materializeLargeCMVal(I, GV, OpFlags);
2297       I.eraseFromParent();
2298       return true;
2299     } else if (TM.getCodeModel() == CodeModel::Tiny) {
2300       I.setDesc(TII.get(AArch64::ADR));
2301       I.getOperand(1).setTargetFlags(OpFlags);
2302     } else {
2303       I.setDesc(TII.get(AArch64::MOVaddr));
2304       I.getOperand(1).setTargetFlags(OpFlags | AArch64II::MO_PAGE);
2305       MachineInstrBuilder MIB(MF, I);
2306       MIB.addGlobalAddress(GV, I.getOperand(1).getOffset(),
2307                            OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
2308     }
2309     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2310   }
2311 
2312   case TargetOpcode::G_ZEXTLOAD:
2313   case TargetOpcode::G_LOAD:
2314   case TargetOpcode::G_STORE: {
2315     bool IsZExtLoad = I.getOpcode() == TargetOpcode::G_ZEXTLOAD;
2316     MachineIRBuilder MIB(I);
2317 
2318     LLT PtrTy = MRI.getType(I.getOperand(1).getReg());
2319 
2320     if (PtrTy != LLT::pointer(0, 64)) {
2321       LLVM_DEBUG(dbgs() << "Load/Store pointer has type: " << PtrTy
2322                         << ", expected: " << LLT::pointer(0, 64) << '\n');
2323       return false;
2324     }
2325 
2326     auto &MemOp = **I.memoperands_begin();
2327     uint64_t MemSizeInBytes = MemOp.getSize();
2328     if (MemOp.isAtomic()) {
2329       // For now we just support s8 acquire loads to be able to compile stack
2330       // protector code.
2331       if (MemOp.getOrdering() == AtomicOrdering::Acquire &&
2332           MemSizeInBytes == 1) {
2333         I.setDesc(TII.get(AArch64::LDARB));
2334         return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2335       }
2336       LLVM_DEBUG(dbgs() << "Atomic load/store not fully supported yet\n");
2337       return false;
2338     }
2339     unsigned MemSizeInBits = MemSizeInBytes * 8;
2340 
2341 #ifndef NDEBUG
2342     const Register PtrReg = I.getOperand(1).getReg();
2343     const RegisterBank &PtrRB = *RBI.getRegBank(PtrReg, MRI, TRI);
2344     // Sanity-check the pointer register.
2345     assert(PtrRB.getID() == AArch64::GPRRegBankID &&
2346            "Load/Store pointer operand isn't a GPR");
2347     assert(MRI.getType(PtrReg).isPointer() &&
2348            "Load/Store pointer operand isn't a pointer");
2349 #endif
2350 
2351     const Register ValReg = I.getOperand(0).getReg();
2352     const RegisterBank &RB = *RBI.getRegBank(ValReg, MRI, TRI);
2353 
2354     // Helper lambda for partially selecting I. Either returns the original
2355     // instruction with an updated opcode, or a new instruction.
2356     auto SelectLoadStoreAddressingMode = [&]() -> MachineInstr * {
2357       bool IsStore = I.getOpcode() == TargetOpcode::G_STORE;
2358       const unsigned NewOpc =
2359           selectLoadStoreUIOp(I.getOpcode(), RB.getID(), MemSizeInBits);
2360       if (NewOpc == I.getOpcode())
2361         return nullptr;
2362       // Check if we can fold anything into the addressing mode.
2363       auto AddrModeFns =
2364           selectAddrModeIndexed(I.getOperand(1), MemSizeInBytes);
2365       if (!AddrModeFns) {
2366         // Can't fold anything. Use the original instruction.
2367         I.setDesc(TII.get(NewOpc));
2368         I.addOperand(MachineOperand::CreateImm(0));
2369         return &I;
2370       }
2371 
2372       // Folded something. Create a new instruction and return it.
2373       auto NewInst = MIB.buildInstr(NewOpc, {}, {}, I.getFlags());
2374       IsStore ? NewInst.addUse(ValReg) : NewInst.addDef(ValReg);
2375       NewInst.cloneMemRefs(I);
2376       for (auto &Fn : *AddrModeFns)
2377         Fn(NewInst);
2378       I.eraseFromParent();
2379       return &*NewInst;
2380     };
2381 
2382     MachineInstr *LoadStore = SelectLoadStoreAddressingMode();
2383     if (!LoadStore)
2384       return false;
2385 
2386     // If we're storing a 0, use WZR/XZR.
2387     if (Opcode == TargetOpcode::G_STORE) {
2388       auto CVal = getConstantVRegValWithLookThrough(
2389           LoadStore->getOperand(0).getReg(), MRI, /*LookThroughInstrs = */ true,
2390           /*HandleFConstants = */ false);
2391       if (CVal && CVal->Value == 0) {
2392         switch (LoadStore->getOpcode()) {
2393         case AArch64::STRWui:
2394         case AArch64::STRHHui:
2395         case AArch64::STRBBui:
2396           LoadStore->getOperand(0).setReg(AArch64::WZR);
2397           break;
2398         case AArch64::STRXui:
2399           LoadStore->getOperand(0).setReg(AArch64::XZR);
2400           break;
2401         }
2402       }
2403     }
2404 
2405     if (IsZExtLoad) {
2406       // The zextload from a smaller type to i32 should be handled by the
2407       // importer.
2408       if (MRI.getType(LoadStore->getOperand(0).getReg()).getSizeInBits() != 64)
2409         return false;
2410       // If we have a ZEXTLOAD then change the load's type to be a narrower reg
2411       // and zero_extend with SUBREG_TO_REG.
2412       Register LdReg = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
2413       Register DstReg = LoadStore->getOperand(0).getReg();
2414       LoadStore->getOperand(0).setReg(LdReg);
2415 
2416       MIB.setInsertPt(MIB.getMBB(), std::next(LoadStore->getIterator()));
2417       MIB.buildInstr(AArch64::SUBREG_TO_REG, {DstReg}, {})
2418           .addImm(0)
2419           .addUse(LdReg)
2420           .addImm(AArch64::sub_32);
2421       constrainSelectedInstRegOperands(*LoadStore, TII, TRI, RBI);
2422       return RBI.constrainGenericRegister(DstReg, AArch64::GPR64allRegClass,
2423                                           MRI);
2424     }
2425     return constrainSelectedInstRegOperands(*LoadStore, TII, TRI, RBI);
2426   }
2427 
2428   case TargetOpcode::G_SMULH:
2429   case TargetOpcode::G_UMULH: {
2430     // Reject the various things we don't support yet.
2431     if (unsupportedBinOp(I, RBI, MRI, TRI))
2432       return false;
2433 
2434     const Register DefReg = I.getOperand(0).getReg();
2435     const RegisterBank &RB = *RBI.getRegBank(DefReg, MRI, TRI);
2436 
2437     if (RB.getID() != AArch64::GPRRegBankID) {
2438       LLVM_DEBUG(dbgs() << "G_[SU]MULH on bank: " << RB << ", expected: GPR\n");
2439       return false;
2440     }
2441 
2442     if (Ty != LLT::scalar(64)) {
2443       LLVM_DEBUG(dbgs() << "G_[SU]MULH has type: " << Ty
2444                         << ", expected: " << LLT::scalar(64) << '\n');
2445       return false;
2446     }
2447 
2448     unsigned NewOpc = I.getOpcode() == TargetOpcode::G_SMULH ? AArch64::SMULHrr
2449                                                              : AArch64::UMULHrr;
2450     I.setDesc(TII.get(NewOpc));
2451 
2452     // Now that we selected an opcode, we need to constrain the register
2453     // operands to use appropriate classes.
2454     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2455   }
2456   case TargetOpcode::G_LSHR:
2457   case TargetOpcode::G_ASHR:
2458     if (MRI.getType(I.getOperand(0).getReg()).isVector())
2459       return selectVectorAshrLshr(I, MRI);
2460     LLVM_FALLTHROUGH;
2461   case TargetOpcode::G_SHL:
2462     if (Opcode == TargetOpcode::G_SHL &&
2463         MRI.getType(I.getOperand(0).getReg()).isVector())
2464       return selectVectorSHL(I, MRI);
2465     LLVM_FALLTHROUGH;
2466   case TargetOpcode::G_FADD:
2467   case TargetOpcode::G_FSUB:
2468   case TargetOpcode::G_FMUL:
2469   case TargetOpcode::G_FDIV:
2470   case TargetOpcode::G_OR: {
2471     // Reject the various things we don't support yet.
2472     if (unsupportedBinOp(I, RBI, MRI, TRI))
2473       return false;
2474 
2475     const unsigned OpSize = Ty.getSizeInBits();
2476 
2477     const Register DefReg = I.getOperand(0).getReg();
2478     const RegisterBank &RB = *RBI.getRegBank(DefReg, MRI, TRI);
2479 
2480     const unsigned NewOpc = selectBinaryOp(I.getOpcode(), RB.getID(), OpSize);
2481     if (NewOpc == I.getOpcode())
2482       return false;
2483 
2484     I.setDesc(TII.get(NewOpc));
2485     // FIXME: Should the type be always reset in setDesc?
2486 
2487     // Now that we selected an opcode, we need to constrain the register
2488     // operands to use appropriate classes.
2489     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2490   }
2491 
2492   case TargetOpcode::G_PTR_ADD: {
2493     MachineIRBuilder MIRBuilder(I);
2494     emitADD(I.getOperand(0).getReg(), I.getOperand(1), I.getOperand(2),
2495             MIRBuilder);
2496     I.eraseFromParent();
2497     return true;
2498   }
2499   case TargetOpcode::G_UADDO: {
2500     // TODO: Support other types.
2501     unsigned OpSize = Ty.getSizeInBits();
2502     if (OpSize != 32 && OpSize != 64) {
2503       LLVM_DEBUG(
2504           dbgs()
2505           << "G_UADDO currently only supported for 32 and 64 b types.\n");
2506       return false;
2507     }
2508 
2509     // TODO: Support vectors.
2510     if (Ty.isVector()) {
2511       LLVM_DEBUG(dbgs() << "G_UADDO currently only supported for scalars.\n");
2512       return false;
2513     }
2514 
2515     // Add and set the set condition flag.
2516     MachineIRBuilder MIRBuilder(I);
2517     emitADDS(I.getOperand(0).getReg(), I.getOperand(2), I.getOperand(3),
2518              MIRBuilder);
2519 
2520     // Now, put the overflow result in the register given by the first operand
2521     // to the G_UADDO. CSINC increments the result when the predicate is false,
2522     // so to get the increment when it's true, we need to use the inverse. In
2523     // this case, we want to increment when carry is set.
2524     auto CsetMI = MIRBuilder
2525                       .buildInstr(AArch64::CSINCWr, {I.getOperand(1).getReg()},
2526                                   {Register(AArch64::WZR), Register(AArch64::WZR)})
2527                       .addImm(getInvertedCondCode(AArch64CC::HS));
2528     constrainSelectedInstRegOperands(*CsetMI, TII, TRI, RBI);
2529     I.eraseFromParent();
2530     return true;
2531   }
2532 
2533   case TargetOpcode::G_PTRMASK: {
2534     Register MaskReg = I.getOperand(2).getReg();
2535     Optional<int64_t> MaskVal = getConstantVRegVal(MaskReg, MRI);
2536     // TODO: Implement arbitrary cases
2537     if (!MaskVal || !isShiftedMask_64(*MaskVal))
2538       return false;
2539 
2540     uint64_t Mask = *MaskVal;
2541     I.setDesc(TII.get(AArch64::ANDXri));
2542     I.getOperand(2).ChangeToImmediate(
2543         AArch64_AM::encodeLogicalImmediate(Mask, 64));
2544 
2545     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2546   }
2547   case TargetOpcode::G_PTRTOINT:
2548   case TargetOpcode::G_TRUNC: {
2549     const LLT DstTy = MRI.getType(I.getOperand(0).getReg());
2550     const LLT SrcTy = MRI.getType(I.getOperand(1).getReg());
2551 
2552     const Register DstReg = I.getOperand(0).getReg();
2553     const Register SrcReg = I.getOperand(1).getReg();
2554 
2555     const RegisterBank &DstRB = *RBI.getRegBank(DstReg, MRI, TRI);
2556     const RegisterBank &SrcRB = *RBI.getRegBank(SrcReg, MRI, TRI);
2557 
2558     if (DstRB.getID() != SrcRB.getID()) {
2559       LLVM_DEBUG(
2560           dbgs() << "G_TRUNC/G_PTRTOINT input/output on different banks\n");
2561       return false;
2562     }
2563 
2564     if (DstRB.getID() == AArch64::GPRRegBankID) {
2565       const TargetRegisterClass *DstRC =
2566           getRegClassForTypeOnBank(DstTy, DstRB, RBI);
2567       if (!DstRC)
2568         return false;
2569 
2570       const TargetRegisterClass *SrcRC =
2571           getRegClassForTypeOnBank(SrcTy, SrcRB, RBI);
2572       if (!SrcRC)
2573         return false;
2574 
2575       if (!RBI.constrainGenericRegister(SrcReg, *SrcRC, MRI) ||
2576           !RBI.constrainGenericRegister(DstReg, *DstRC, MRI)) {
2577         LLVM_DEBUG(dbgs() << "Failed to constrain G_TRUNC/G_PTRTOINT\n");
2578         return false;
2579       }
2580 
2581       if (DstRC == SrcRC) {
2582         // Nothing to be done
2583       } else if (Opcode == TargetOpcode::G_TRUNC && DstTy == LLT::scalar(32) &&
2584                  SrcTy == LLT::scalar(64)) {
2585         llvm_unreachable("TableGen can import this case");
2586         return false;
2587       } else if (DstRC == &AArch64::GPR32RegClass &&
2588                  SrcRC == &AArch64::GPR64RegClass) {
2589         I.getOperand(1).setSubReg(AArch64::sub_32);
2590       } else {
2591         LLVM_DEBUG(
2592             dbgs() << "Unhandled mismatched classes in G_TRUNC/G_PTRTOINT\n");
2593         return false;
2594       }
2595 
2596       I.setDesc(TII.get(TargetOpcode::COPY));
2597       return true;
2598     } else if (DstRB.getID() == AArch64::FPRRegBankID) {
2599       if (DstTy == LLT::vector(4, 16) && SrcTy == LLT::vector(4, 32)) {
2600         I.setDesc(TII.get(AArch64::XTNv4i16));
2601         constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2602         return true;
2603       }
2604 
2605       if (!SrcTy.isVector() && SrcTy.getSizeInBits() == 128) {
2606         MachineIRBuilder MIB(I);
2607         MachineInstr *Extract = emitExtractVectorElt(
2608             DstReg, DstRB, LLT::scalar(DstTy.getSizeInBits()), SrcReg, 0, MIB);
2609         if (!Extract)
2610           return false;
2611         I.eraseFromParent();
2612         return true;
2613       }
2614 
2615       // We might have a vector G_PTRTOINT, in which case just emit a COPY.
2616       if (Opcode == TargetOpcode::G_PTRTOINT) {
2617         assert(DstTy.isVector() && "Expected an FPR ptrtoint to be a vector");
2618         I.setDesc(TII.get(TargetOpcode::COPY));
2619         return true;
2620       }
2621     }
2622 
2623     return false;
2624   }
2625 
2626   case TargetOpcode::G_ANYEXT: {
2627     const Register DstReg = I.getOperand(0).getReg();
2628     const Register SrcReg = I.getOperand(1).getReg();
2629 
2630     const RegisterBank &RBDst = *RBI.getRegBank(DstReg, MRI, TRI);
2631     if (RBDst.getID() != AArch64::GPRRegBankID) {
2632       LLVM_DEBUG(dbgs() << "G_ANYEXT on bank: " << RBDst
2633                         << ", expected: GPR\n");
2634       return false;
2635     }
2636 
2637     const RegisterBank &RBSrc = *RBI.getRegBank(SrcReg, MRI, TRI);
2638     if (RBSrc.getID() != AArch64::GPRRegBankID) {
2639       LLVM_DEBUG(dbgs() << "G_ANYEXT on bank: " << RBSrc
2640                         << ", expected: GPR\n");
2641       return false;
2642     }
2643 
2644     const unsigned DstSize = MRI.getType(DstReg).getSizeInBits();
2645 
2646     if (DstSize == 0) {
2647       LLVM_DEBUG(dbgs() << "G_ANYEXT operand has no size, not a gvreg?\n");
2648       return false;
2649     }
2650 
2651     if (DstSize != 64 && DstSize > 32) {
2652       LLVM_DEBUG(dbgs() << "G_ANYEXT to size: " << DstSize
2653                         << ", expected: 32 or 64\n");
2654       return false;
2655     }
2656     // At this point G_ANYEXT is just like a plain COPY, but we need
2657     // to explicitly form the 64-bit value if any.
2658     if (DstSize > 32) {
2659       Register ExtSrc = MRI.createVirtualRegister(&AArch64::GPR64allRegClass);
2660       BuildMI(MBB, I, I.getDebugLoc(), TII.get(AArch64::SUBREG_TO_REG))
2661           .addDef(ExtSrc)
2662           .addImm(0)
2663           .addUse(SrcReg)
2664           .addImm(AArch64::sub_32);
2665       I.getOperand(1).setReg(ExtSrc);
2666     }
2667     return selectCopy(I, TII, MRI, TRI, RBI);
2668   }
2669 
2670   case TargetOpcode::G_ZEXT:
2671   case TargetOpcode::G_SEXT_INREG:
2672   case TargetOpcode::G_SEXT: {
2673     unsigned Opcode = I.getOpcode();
2674     const bool IsSigned = Opcode != TargetOpcode::G_ZEXT;
2675     const Register DefReg = I.getOperand(0).getReg();
2676     Register SrcReg = I.getOperand(1).getReg();
2677     const LLT DstTy = MRI.getType(DefReg);
2678     const LLT SrcTy = MRI.getType(SrcReg);
2679     unsigned DstSize = DstTy.getSizeInBits();
2680     unsigned SrcSize = SrcTy.getSizeInBits();
2681 
2682     // SEXT_INREG has the same src reg size as dst, the size of the value to be
2683     // extended is encoded in the imm.
2684     if (Opcode == TargetOpcode::G_SEXT_INREG)
2685       SrcSize = I.getOperand(2).getImm();
2686 
2687     if (DstTy.isVector())
2688       return false; // Should be handled by imported patterns.
2689 
2690     assert((*RBI.getRegBank(DefReg, MRI, TRI)).getID() ==
2691                AArch64::GPRRegBankID &&
2692            "Unexpected ext regbank");
2693 
2694     MachineIRBuilder MIB(I);
2695     MachineInstr *ExtI;
2696 
2697     // First check if we're extending the result of a load which has a dest type
2698     // smaller than 32 bits, then this zext is redundant. GPR32 is the smallest
2699     // GPR register on AArch64 and all loads which are smaller automatically
2700     // zero-extend the upper bits. E.g.
2701     // %v(s8) = G_LOAD %p, :: (load 1)
2702     // %v2(s32) = G_ZEXT %v(s8)
2703     if (!IsSigned) {
2704       auto *LoadMI = getOpcodeDef(TargetOpcode::G_LOAD, SrcReg, MRI);
2705       bool IsGPR =
2706           RBI.getRegBank(SrcReg, MRI, TRI)->getID() == AArch64::GPRRegBankID;
2707       if (LoadMI && IsGPR) {
2708         const MachineMemOperand *MemOp = *LoadMI->memoperands_begin();
2709         unsigned BytesLoaded = MemOp->getSize();
2710         if (BytesLoaded < 4 && SrcTy.getSizeInBytes() == BytesLoaded)
2711           return selectCopy(I, TII, MRI, TRI, RBI);
2712       }
2713 
2714       // If we are zero extending from 32 bits to 64 bits, it's possible that
2715       // the instruction implicitly does the zero extend for us. In that case,
2716       // we can just emit a SUBREG_TO_REG.
2717       if (IsGPR && SrcSize == 32 && DstSize == 64) {
2718         // Unlike with the G_LOAD case, we don't want to look through copies
2719         // here.
2720         MachineInstr *Def = MRI.getVRegDef(SrcReg);
2721         if (Def && isDef32(*Def)) {
2722           MIB.buildInstr(AArch64::SUBREG_TO_REG, {DefReg}, {})
2723               .addImm(0)
2724               .addUse(SrcReg)
2725               .addImm(AArch64::sub_32);
2726 
2727           if (!RBI.constrainGenericRegister(DefReg, AArch64::GPR64RegClass,
2728                                             MRI)) {
2729             LLVM_DEBUG(dbgs() << "Failed to constrain G_ZEXT destination\n");
2730             return false;
2731           }
2732 
2733           if (!RBI.constrainGenericRegister(SrcReg, AArch64::GPR32RegClass,
2734                                             MRI)) {
2735             LLVM_DEBUG(dbgs() << "Failed to constrain G_ZEXT source\n");
2736             return false;
2737           }
2738 
2739           I.eraseFromParent();
2740           return true;
2741         }
2742       }
2743     }
2744 
2745     if (DstSize == 64) {
2746       if (Opcode != TargetOpcode::G_SEXT_INREG) {
2747         // FIXME: Can we avoid manually doing this?
2748         if (!RBI.constrainGenericRegister(SrcReg, AArch64::GPR32RegClass,
2749                                           MRI)) {
2750           LLVM_DEBUG(dbgs() << "Failed to constrain " << TII.getName(Opcode)
2751                             << " operand\n");
2752           return false;
2753         }
2754         SrcReg = MIB.buildInstr(AArch64::SUBREG_TO_REG,
2755                                 {&AArch64::GPR64RegClass}, {})
2756                      .addImm(0)
2757                      .addUse(SrcReg)
2758                      .addImm(AArch64::sub_32)
2759                      .getReg(0);
2760       }
2761 
2762       ExtI = MIB.buildInstr(IsSigned ? AArch64::SBFMXri : AArch64::UBFMXri,
2763                              {DefReg}, {SrcReg})
2764                   .addImm(0)
2765                   .addImm(SrcSize - 1);
2766     } else if (DstSize <= 32) {
2767       ExtI = MIB.buildInstr(IsSigned ? AArch64::SBFMWri : AArch64::UBFMWri,
2768                              {DefReg}, {SrcReg})
2769                   .addImm(0)
2770                   .addImm(SrcSize - 1);
2771     } else {
2772       return false;
2773     }
2774 
2775     constrainSelectedInstRegOperands(*ExtI, TII, TRI, RBI);
2776     I.eraseFromParent();
2777     return true;
2778   }
2779 
2780   case TargetOpcode::G_SITOFP:
2781   case TargetOpcode::G_UITOFP:
2782   case TargetOpcode::G_FPTOSI:
2783   case TargetOpcode::G_FPTOUI: {
2784     const LLT DstTy = MRI.getType(I.getOperand(0).getReg()),
2785               SrcTy = MRI.getType(I.getOperand(1).getReg());
2786     const unsigned NewOpc = selectFPConvOpc(Opcode, DstTy, SrcTy);
2787     if (NewOpc == Opcode)
2788       return false;
2789 
2790     I.setDesc(TII.get(NewOpc));
2791     constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2792 
2793     return true;
2794   }
2795 
2796   case TargetOpcode::G_FREEZE:
2797     return selectCopy(I, TII, MRI, TRI, RBI);
2798 
2799   case TargetOpcode::G_INTTOPTR:
2800     // The importer is currently unable to import pointer types since they
2801     // didn't exist in SelectionDAG.
2802     return selectCopy(I, TII, MRI, TRI, RBI);
2803 
2804   case TargetOpcode::G_BITCAST:
2805     // Imported SelectionDAG rules can handle every bitcast except those that
2806     // bitcast from a type to the same type. Ideally, these shouldn't occur
2807     // but we might not run an optimizer that deletes them. The other exception
2808     // is bitcasts involving pointer types, as SelectionDAG has no knowledge
2809     // of them.
2810     return selectCopy(I, TII, MRI, TRI, RBI);
2811 
2812   case TargetOpcode::G_SELECT: {
2813     if (MRI.getType(I.getOperand(1).getReg()) != LLT::scalar(1)) {
2814       LLVM_DEBUG(dbgs() << "G_SELECT cond has type: " << Ty
2815                         << ", expected: " << LLT::scalar(1) << '\n');
2816       return false;
2817     }
2818 
2819     const Register CondReg = I.getOperand(1).getReg();
2820     const Register TReg = I.getOperand(2).getReg();
2821     const Register FReg = I.getOperand(3).getReg();
2822 
2823     if (tryOptSelect(I))
2824       return true;
2825 
2826     Register CSelOpc = selectSelectOpc(I, MRI, RBI);
2827     // Make sure to use an unused vreg instead of wzr, so that the peephole
2828     // optimizations will be able to optimize these.
2829     Register DeadVReg = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
2830     MachineInstr &TstMI =
2831         *BuildMI(MBB, I, I.getDebugLoc(), TII.get(AArch64::ANDSWri))
2832              .addDef(DeadVReg)
2833              .addUse(CondReg)
2834              .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
2835 
2836     MachineInstr &CSelMI = *BuildMI(MBB, I, I.getDebugLoc(), TII.get(CSelOpc))
2837                                 .addDef(I.getOperand(0).getReg())
2838                                 .addUse(TReg)
2839                                 .addUse(FReg)
2840                                 .addImm(AArch64CC::NE);
2841 
2842     constrainSelectedInstRegOperands(TstMI, TII, TRI, RBI);
2843     constrainSelectedInstRegOperands(CSelMI, TII, TRI, RBI);
2844 
2845     I.eraseFromParent();
2846     return true;
2847   }
2848   case TargetOpcode::G_ICMP: {
2849     if (Ty.isVector())
2850       return selectVectorICmp(I, MRI);
2851 
2852     if (Ty != LLT::scalar(32)) {
2853       LLVM_DEBUG(dbgs() << "G_ICMP result has type: " << Ty
2854                         << ", expected: " << LLT::scalar(32) << '\n');
2855       return false;
2856     }
2857 
2858     MachineIRBuilder MIRBuilder(I);
2859     auto Pred = static_cast<CmpInst::Predicate>(I.getOperand(1).getPredicate());
2860     emitIntegerCompare(I.getOperand(2), I.getOperand(3), I.getOperand(1),
2861                        MIRBuilder);
2862     emitCSetForICMP(I.getOperand(0).getReg(), Pred, MIRBuilder);
2863     I.eraseFromParent();
2864     return true;
2865   }
2866 
2867   case TargetOpcode::G_FCMP: {
2868     MachineIRBuilder MIRBuilder(I);
2869     CmpInst::Predicate Pred =
2870         static_cast<CmpInst::Predicate>(I.getOperand(1).getPredicate());
2871     if (!emitFPCompare(I.getOperand(2).getReg(), I.getOperand(3).getReg(),
2872                        MIRBuilder) ||
2873         !emitCSetForFCmp(I.getOperand(0).getReg(), Pred, MIRBuilder))
2874       return false;
2875     I.eraseFromParent();
2876     return true;
2877   }
2878   case TargetOpcode::G_VASTART:
2879     return STI.isTargetDarwin() ? selectVaStartDarwin(I, MF, MRI)
2880                                 : selectVaStartAAPCS(I, MF, MRI);
2881   case TargetOpcode::G_INTRINSIC:
2882     return selectIntrinsic(I, MRI);
2883   case TargetOpcode::G_INTRINSIC_W_SIDE_EFFECTS:
2884     return selectIntrinsicWithSideEffects(I, MRI);
2885   case TargetOpcode::G_IMPLICIT_DEF: {
2886     I.setDesc(TII.get(TargetOpcode::IMPLICIT_DEF));
2887     const LLT DstTy = MRI.getType(I.getOperand(0).getReg());
2888     const Register DstReg = I.getOperand(0).getReg();
2889     const RegisterBank &DstRB = *RBI.getRegBank(DstReg, MRI, TRI);
2890     const TargetRegisterClass *DstRC =
2891         getRegClassForTypeOnBank(DstTy, DstRB, RBI);
2892     RBI.constrainGenericRegister(DstReg, *DstRC, MRI);
2893     return true;
2894   }
2895   case TargetOpcode::G_BLOCK_ADDR: {
2896     if (TM.getCodeModel() == CodeModel::Large) {
2897       materializeLargeCMVal(I, I.getOperand(1).getBlockAddress(), 0);
2898       I.eraseFromParent();
2899       return true;
2900     } else {
2901       I.setDesc(TII.get(AArch64::MOVaddrBA));
2902       auto MovMI = BuildMI(MBB, I, I.getDebugLoc(), TII.get(AArch64::MOVaddrBA),
2903                            I.getOperand(0).getReg())
2904                        .addBlockAddress(I.getOperand(1).getBlockAddress(),
2905                                         /* Offset */ 0, AArch64II::MO_PAGE)
2906                        .addBlockAddress(
2907                            I.getOperand(1).getBlockAddress(), /* Offset */ 0,
2908                            AArch64II::MO_NC | AArch64II::MO_PAGEOFF);
2909       I.eraseFromParent();
2910       return constrainSelectedInstRegOperands(*MovMI, TII, TRI, RBI);
2911     }
2912   }
2913   case AArch64::G_DUP: {
2914     // When the scalar of G_DUP is an s8/s16 gpr, they can't be selected by
2915     // imported patterns. Do it manually here. Avoiding generating s16 gpr is
2916     // difficult because at RBS we may end up pessimizing the fpr case if we
2917     // decided to add an anyextend to fix this. Manual selection is the most
2918     // robust solution for now.
2919     Register SrcReg = I.getOperand(1).getReg();
2920     if (RBI.getRegBank(SrcReg, MRI, TRI)->getID() != AArch64::GPRRegBankID)
2921       return false; // We expect the fpr regbank case to be imported.
2922     LLT SrcTy = MRI.getType(SrcReg);
2923     if (SrcTy.getSizeInBits() == 16)
2924       I.setDesc(TII.get(AArch64::DUPv8i16gpr));
2925     else if (SrcTy.getSizeInBits() == 8)
2926       I.setDesc(TII.get(AArch64::DUPv16i8gpr));
2927     else
2928       return false;
2929     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2930   }
2931   case TargetOpcode::G_INTRINSIC_TRUNC:
2932     return selectIntrinsicTrunc(I, MRI);
2933   case TargetOpcode::G_INTRINSIC_ROUND:
2934     return selectIntrinsicRound(I, MRI);
2935   case TargetOpcode::G_BUILD_VECTOR:
2936     return selectBuildVector(I, MRI);
2937   case TargetOpcode::G_MERGE_VALUES:
2938     return selectMergeValues(I, MRI);
2939   case TargetOpcode::G_UNMERGE_VALUES:
2940     return selectUnmergeValues(I, MRI);
2941   case TargetOpcode::G_SHUFFLE_VECTOR:
2942     return selectShuffleVector(I, MRI);
2943   case TargetOpcode::G_EXTRACT_VECTOR_ELT:
2944     return selectExtractElt(I, MRI);
2945   case TargetOpcode::G_INSERT_VECTOR_ELT:
2946     return selectInsertElt(I, MRI);
2947   case TargetOpcode::G_CONCAT_VECTORS:
2948     return selectConcatVectors(I, MRI);
2949   case TargetOpcode::G_JUMP_TABLE:
2950     return selectJumpTable(I, MRI);
2951   case TargetOpcode::G_VECREDUCE_FADD:
2952   case TargetOpcode::G_VECREDUCE_ADD:
2953     return selectReduction(I, MRI);
2954   }
2955 
2956   return false;
2957 }
2958 
2959 bool AArch64InstructionSelector::selectReduction(
2960     MachineInstr &I, MachineRegisterInfo &MRI) const {
2961   Register VecReg = I.getOperand(1).getReg();
2962   LLT VecTy = MRI.getType(VecReg);
2963   if (I.getOpcode() == TargetOpcode::G_VECREDUCE_ADD) {
2964     unsigned Opc = 0;
2965     if (VecTy == LLT::vector(16, 8))
2966       Opc = AArch64::ADDVv16i8v;
2967     else if (VecTy == LLT::vector(8, 16))
2968       Opc = AArch64::ADDVv8i16v;
2969     else if (VecTy == LLT::vector(4, 32))
2970       Opc = AArch64::ADDVv4i32v;
2971     else if (VecTy == LLT::vector(2, 64))
2972       Opc = AArch64::ADDPv2i64p;
2973     else {
2974       LLVM_DEBUG(dbgs() << "Unhandled type for add reduction");
2975       return false;
2976     }
2977     I.setDesc(TII.get(Opc));
2978     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2979   }
2980 
2981   if (I.getOpcode() == TargetOpcode::G_VECREDUCE_FADD) {
2982     unsigned Opc = 0;
2983     if (VecTy == LLT::vector(2, 32))
2984       Opc = AArch64::FADDPv2i32p;
2985     else if (VecTy == LLT::vector(2, 64))
2986       Opc = AArch64::FADDPv2i64p;
2987     else {
2988       LLVM_DEBUG(dbgs() << "Unhandled type for fadd reduction");
2989       return false;
2990     }
2991     I.setDesc(TII.get(Opc));
2992     return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
2993   }
2994   return false;
2995 }
2996 
2997 bool AArch64InstructionSelector::selectBrJT(MachineInstr &I,
2998                                             MachineRegisterInfo &MRI) const {
2999   assert(I.getOpcode() == TargetOpcode::G_BRJT && "Expected G_BRJT");
3000   Register JTAddr = I.getOperand(0).getReg();
3001   unsigned JTI = I.getOperand(1).getIndex();
3002   Register Index = I.getOperand(2).getReg();
3003   MachineIRBuilder MIB(I);
3004 
3005   Register TargetReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3006   Register ScratchReg = MRI.createVirtualRegister(&AArch64::GPR64spRegClass);
3007 
3008   MF->getInfo<AArch64FunctionInfo>()->setJumpTableEntryInfo(JTI, 4, nullptr);
3009   auto JumpTableInst = MIB.buildInstr(AArch64::JumpTableDest32,
3010                                       {TargetReg, ScratchReg}, {JTAddr, Index})
3011                            .addJumpTableIndex(JTI);
3012   // Build the indirect branch.
3013   MIB.buildInstr(AArch64::BR, {}, {TargetReg});
3014   I.eraseFromParent();
3015   return constrainSelectedInstRegOperands(*JumpTableInst, TII, TRI, RBI);
3016 }
3017 
3018 bool AArch64InstructionSelector::selectJumpTable(
3019     MachineInstr &I, MachineRegisterInfo &MRI) const {
3020   assert(I.getOpcode() == TargetOpcode::G_JUMP_TABLE && "Expected jump table");
3021   assert(I.getOperand(1).isJTI() && "Jump table op should have a JTI!");
3022 
3023   Register DstReg = I.getOperand(0).getReg();
3024   unsigned JTI = I.getOperand(1).getIndex();
3025   // We generate a MOVaddrJT which will get expanded to an ADRP + ADD later.
3026   MachineIRBuilder MIB(I);
3027   auto MovMI =
3028     MIB.buildInstr(AArch64::MOVaddrJT, {DstReg}, {})
3029           .addJumpTableIndex(JTI, AArch64II::MO_PAGE)
3030           .addJumpTableIndex(JTI, AArch64II::MO_NC | AArch64II::MO_PAGEOFF);
3031   I.eraseFromParent();
3032   return constrainSelectedInstRegOperands(*MovMI, TII, TRI, RBI);
3033 }
3034 
3035 bool AArch64InstructionSelector::selectTLSGlobalValue(
3036     MachineInstr &I, MachineRegisterInfo &MRI) const {
3037   if (!STI.isTargetMachO())
3038     return false;
3039   MachineFunction &MF = *I.getParent()->getParent();
3040   MF.getFrameInfo().setAdjustsStack(true);
3041 
3042   const GlobalValue &GV = *I.getOperand(1).getGlobal();
3043   MachineIRBuilder MIB(I);
3044 
3045   auto LoadGOT =
3046       MIB.buildInstr(AArch64::LOADgot, {&AArch64::GPR64commonRegClass}, {})
3047           .addGlobalAddress(&GV, 0, AArch64II::MO_TLS);
3048 
3049   auto Load = MIB.buildInstr(AArch64::LDRXui, {&AArch64::GPR64commonRegClass},
3050                              {LoadGOT.getReg(0)})
3051                   .addImm(0);
3052 
3053   MIB.buildCopy(Register(AArch64::X0), LoadGOT.getReg(0));
3054   // TLS calls preserve all registers except those that absolutely must be
3055   // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3056   // silly).
3057   MIB.buildInstr(getBLRCallOpcode(MF), {}, {Load})
3058       .addUse(AArch64::X0, RegState::Implicit)
3059       .addDef(AArch64::X0, RegState::Implicit)
3060       .addRegMask(TRI.getTLSCallPreservedMask());
3061 
3062   MIB.buildCopy(I.getOperand(0).getReg(), Register(AArch64::X0));
3063   RBI.constrainGenericRegister(I.getOperand(0).getReg(), AArch64::GPR64RegClass,
3064                                MRI);
3065   I.eraseFromParent();
3066   return true;
3067 }
3068 
3069 bool AArch64InstructionSelector::selectIntrinsicTrunc(
3070     MachineInstr &I, MachineRegisterInfo &MRI) const {
3071   const LLT SrcTy = MRI.getType(I.getOperand(0).getReg());
3072 
3073   // Select the correct opcode.
3074   unsigned Opc = 0;
3075   if (!SrcTy.isVector()) {
3076     switch (SrcTy.getSizeInBits()) {
3077     default:
3078     case 16:
3079       Opc = AArch64::FRINTZHr;
3080       break;
3081     case 32:
3082       Opc = AArch64::FRINTZSr;
3083       break;
3084     case 64:
3085       Opc = AArch64::FRINTZDr;
3086       break;
3087     }
3088   } else {
3089     unsigned NumElts = SrcTy.getNumElements();
3090     switch (SrcTy.getElementType().getSizeInBits()) {
3091     default:
3092       break;
3093     case 16:
3094       if (NumElts == 4)
3095         Opc = AArch64::FRINTZv4f16;
3096       else if (NumElts == 8)
3097         Opc = AArch64::FRINTZv8f16;
3098       break;
3099     case 32:
3100       if (NumElts == 2)
3101         Opc = AArch64::FRINTZv2f32;
3102       else if (NumElts == 4)
3103         Opc = AArch64::FRINTZv4f32;
3104       break;
3105     case 64:
3106       if (NumElts == 2)
3107         Opc = AArch64::FRINTZv2f64;
3108       break;
3109     }
3110   }
3111 
3112   if (!Opc) {
3113     // Didn't get an opcode above, bail.
3114     LLVM_DEBUG(dbgs() << "Unsupported type for G_INTRINSIC_TRUNC!\n");
3115     return false;
3116   }
3117 
3118   // Legalization would have set us up perfectly for this; we just need to
3119   // set the opcode and move on.
3120   I.setDesc(TII.get(Opc));
3121   return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
3122 }
3123 
3124 bool AArch64InstructionSelector::selectIntrinsicRound(
3125     MachineInstr &I, MachineRegisterInfo &MRI) const {
3126   const LLT SrcTy = MRI.getType(I.getOperand(0).getReg());
3127 
3128   // Select the correct opcode.
3129   unsigned Opc = 0;
3130   if (!SrcTy.isVector()) {
3131     switch (SrcTy.getSizeInBits()) {
3132     default:
3133     case 16:
3134       Opc = AArch64::FRINTAHr;
3135       break;
3136     case 32:
3137       Opc = AArch64::FRINTASr;
3138       break;
3139     case 64:
3140       Opc = AArch64::FRINTADr;
3141       break;
3142     }
3143   } else {
3144     unsigned NumElts = SrcTy.getNumElements();
3145     switch (SrcTy.getElementType().getSizeInBits()) {
3146     default:
3147       break;
3148     case 16:
3149       if (NumElts == 4)
3150         Opc = AArch64::FRINTAv4f16;
3151       else if (NumElts == 8)
3152         Opc = AArch64::FRINTAv8f16;
3153       break;
3154     case 32:
3155       if (NumElts == 2)
3156         Opc = AArch64::FRINTAv2f32;
3157       else if (NumElts == 4)
3158         Opc = AArch64::FRINTAv4f32;
3159       break;
3160     case 64:
3161       if (NumElts == 2)
3162         Opc = AArch64::FRINTAv2f64;
3163       break;
3164     }
3165   }
3166 
3167   if (!Opc) {
3168     // Didn't get an opcode above, bail.
3169     LLVM_DEBUG(dbgs() << "Unsupported type for G_INTRINSIC_ROUND!\n");
3170     return false;
3171   }
3172 
3173   // Legalization would have set us up perfectly for this; we just need to
3174   // set the opcode and move on.
3175   I.setDesc(TII.get(Opc));
3176   return constrainSelectedInstRegOperands(I, TII, TRI, RBI);
3177 }
3178 
3179 bool AArch64InstructionSelector::selectVectorICmp(
3180     MachineInstr &I, MachineRegisterInfo &MRI) const {
3181   Register DstReg = I.getOperand(0).getReg();
3182   LLT DstTy = MRI.getType(DstReg);
3183   Register SrcReg = I.getOperand(2).getReg();
3184   Register Src2Reg = I.getOperand(3).getReg();
3185   LLT SrcTy = MRI.getType(SrcReg);
3186 
3187   unsigned SrcEltSize = SrcTy.getElementType().getSizeInBits();
3188   unsigned NumElts = DstTy.getNumElements();
3189 
3190   // First index is element size, 0 == 8b, 1 == 16b, 2 == 32b, 3 == 64b
3191   // Second index is num elts, 0 == v2, 1 == v4, 2 == v8, 3 == v16
3192   // Third index is cc opcode:
3193   // 0 == eq
3194   // 1 == ugt
3195   // 2 == uge
3196   // 3 == ult
3197   // 4 == ule
3198   // 5 == sgt
3199   // 6 == sge
3200   // 7 == slt
3201   // 8 == sle
3202   // ne is done by negating 'eq' result.
3203 
3204   // This table below assumes that for some comparisons the operands will be
3205   // commuted.
3206   // ult op == commute + ugt op
3207   // ule op == commute + uge op
3208   // slt op == commute + sgt op
3209   // sle op == commute + sge op
3210   unsigned PredIdx = 0;
3211   bool SwapOperands = false;
3212   CmpInst::Predicate Pred = (CmpInst::Predicate)I.getOperand(1).getPredicate();
3213   switch (Pred) {
3214   case CmpInst::ICMP_NE:
3215   case CmpInst::ICMP_EQ:
3216     PredIdx = 0;
3217     break;
3218   case CmpInst::ICMP_UGT:
3219     PredIdx = 1;
3220     break;
3221   case CmpInst::ICMP_UGE:
3222     PredIdx = 2;
3223     break;
3224   case CmpInst::ICMP_ULT:
3225     PredIdx = 3;
3226     SwapOperands = true;
3227     break;
3228   case CmpInst::ICMP_ULE:
3229     PredIdx = 4;
3230     SwapOperands = true;
3231     break;
3232   case CmpInst::ICMP_SGT:
3233     PredIdx = 5;
3234     break;
3235   case CmpInst::ICMP_SGE:
3236     PredIdx = 6;
3237     break;
3238   case CmpInst::ICMP_SLT:
3239     PredIdx = 7;
3240     SwapOperands = true;
3241     break;
3242   case CmpInst::ICMP_SLE:
3243     PredIdx = 8;
3244     SwapOperands = true;
3245     break;
3246   default:
3247     llvm_unreachable("Unhandled icmp predicate");
3248     return false;
3249   }
3250 
3251   // This table obviously should be tablegen'd when we have our GISel native
3252   // tablegen selector.
3253 
3254   static const unsigned OpcTable[4][4][9] = {
3255       {
3256           {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3257            0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3258            0 /* invalid */},
3259           {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3260            0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3261            0 /* invalid */},
3262           {AArch64::CMEQv8i8, AArch64::CMHIv8i8, AArch64::CMHSv8i8,
3263            AArch64::CMHIv8i8, AArch64::CMHSv8i8, AArch64::CMGTv8i8,
3264            AArch64::CMGEv8i8, AArch64::CMGTv8i8, AArch64::CMGEv8i8},
3265           {AArch64::CMEQv16i8, AArch64::CMHIv16i8, AArch64::CMHSv16i8,
3266            AArch64::CMHIv16i8, AArch64::CMHSv16i8, AArch64::CMGTv16i8,
3267            AArch64::CMGEv16i8, AArch64::CMGTv16i8, AArch64::CMGEv16i8}
3268       },
3269       {
3270           {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3271            0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3272            0 /* invalid */},
3273           {AArch64::CMEQv4i16, AArch64::CMHIv4i16, AArch64::CMHSv4i16,
3274            AArch64::CMHIv4i16, AArch64::CMHSv4i16, AArch64::CMGTv4i16,
3275            AArch64::CMGEv4i16, AArch64::CMGTv4i16, AArch64::CMGEv4i16},
3276           {AArch64::CMEQv8i16, AArch64::CMHIv8i16, AArch64::CMHSv8i16,
3277            AArch64::CMHIv8i16, AArch64::CMHSv8i16, AArch64::CMGTv8i16,
3278            AArch64::CMGEv8i16, AArch64::CMGTv8i16, AArch64::CMGEv8i16},
3279           {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3280            0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3281            0 /* invalid */}
3282       },
3283       {
3284           {AArch64::CMEQv2i32, AArch64::CMHIv2i32, AArch64::CMHSv2i32,
3285            AArch64::CMHIv2i32, AArch64::CMHSv2i32, AArch64::CMGTv2i32,
3286            AArch64::CMGEv2i32, AArch64::CMGTv2i32, AArch64::CMGEv2i32},
3287           {AArch64::CMEQv4i32, AArch64::CMHIv4i32, AArch64::CMHSv4i32,
3288            AArch64::CMHIv4i32, AArch64::CMHSv4i32, AArch64::CMGTv4i32,
3289            AArch64::CMGEv4i32, AArch64::CMGTv4i32, AArch64::CMGEv4i32},
3290           {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3291            0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3292            0 /* invalid */},
3293           {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3294            0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3295            0 /* invalid */}
3296       },
3297       {
3298           {AArch64::CMEQv2i64, AArch64::CMHIv2i64, AArch64::CMHSv2i64,
3299            AArch64::CMHIv2i64, AArch64::CMHSv2i64, AArch64::CMGTv2i64,
3300            AArch64::CMGEv2i64, AArch64::CMGTv2i64, AArch64::CMGEv2i64},
3301           {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3302            0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3303            0 /* invalid */},
3304           {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3305            0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3306            0 /* invalid */},
3307           {0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3308            0 /* invalid */, 0 /* invalid */, 0 /* invalid */, 0 /* invalid */,
3309            0 /* invalid */}
3310       },
3311   };
3312   unsigned EltIdx = Log2_32(SrcEltSize / 8);
3313   unsigned NumEltsIdx = Log2_32(NumElts / 2);
3314   unsigned Opc = OpcTable[EltIdx][NumEltsIdx][PredIdx];
3315   if (!Opc) {
3316     LLVM_DEBUG(dbgs() << "Could not map G_ICMP to cmp opcode");
3317     return false;
3318   }
3319 
3320   const RegisterBank &VecRB = *RBI.getRegBank(SrcReg, MRI, TRI);
3321   const TargetRegisterClass *SrcRC =
3322       getRegClassForTypeOnBank(SrcTy, VecRB, RBI, true);
3323   if (!SrcRC) {
3324     LLVM_DEBUG(dbgs() << "Could not determine source register class.\n");
3325     return false;
3326   }
3327 
3328   unsigned NotOpc = Pred == ICmpInst::ICMP_NE ? AArch64::NOTv8i8 : 0;
3329   if (SrcTy.getSizeInBits() == 128)
3330     NotOpc = NotOpc ? AArch64::NOTv16i8 : 0;
3331 
3332   if (SwapOperands)
3333     std::swap(SrcReg, Src2Reg);
3334 
3335   MachineIRBuilder MIB(I);
3336   auto Cmp = MIB.buildInstr(Opc, {SrcRC}, {SrcReg, Src2Reg});
3337   constrainSelectedInstRegOperands(*Cmp, TII, TRI, RBI);
3338 
3339   // Invert if we had a 'ne' cc.
3340   if (NotOpc) {
3341     Cmp = MIB.buildInstr(NotOpc, {DstReg}, {Cmp});
3342     constrainSelectedInstRegOperands(*Cmp, TII, TRI, RBI);
3343   } else {
3344     MIB.buildCopy(DstReg, Cmp.getReg(0));
3345   }
3346   RBI.constrainGenericRegister(DstReg, *SrcRC, MRI);
3347   I.eraseFromParent();
3348   return true;
3349 }
3350 
3351 MachineInstr *AArch64InstructionSelector::emitScalarToVector(
3352     unsigned EltSize, const TargetRegisterClass *DstRC, Register Scalar,
3353     MachineIRBuilder &MIRBuilder) const {
3354   auto Undef = MIRBuilder.buildInstr(TargetOpcode::IMPLICIT_DEF, {DstRC}, {});
3355 
3356   auto BuildFn = [&](unsigned SubregIndex) {
3357     auto Ins =
3358         MIRBuilder
3359             .buildInstr(TargetOpcode::INSERT_SUBREG, {DstRC}, {Undef, Scalar})
3360             .addImm(SubregIndex);
3361     constrainSelectedInstRegOperands(*Undef, TII, TRI, RBI);
3362     constrainSelectedInstRegOperands(*Ins, TII, TRI, RBI);
3363     return &*Ins;
3364   };
3365 
3366   switch (EltSize) {
3367   case 16:
3368     return BuildFn(AArch64::hsub);
3369   case 32:
3370     return BuildFn(AArch64::ssub);
3371   case 64:
3372     return BuildFn(AArch64::dsub);
3373   default:
3374     return nullptr;
3375   }
3376 }
3377 
3378 bool AArch64InstructionSelector::selectMergeValues(
3379     MachineInstr &I, MachineRegisterInfo &MRI) const {
3380   assert(I.getOpcode() == TargetOpcode::G_MERGE_VALUES && "unexpected opcode");
3381   const LLT DstTy = MRI.getType(I.getOperand(0).getReg());
3382   const LLT SrcTy = MRI.getType(I.getOperand(1).getReg());
3383   assert(!DstTy.isVector() && !SrcTy.isVector() && "invalid merge operation");
3384   const RegisterBank &RB = *RBI.getRegBank(I.getOperand(1).getReg(), MRI, TRI);
3385 
3386   if (I.getNumOperands() != 3)
3387     return false;
3388 
3389   // Merging 2 s64s into an s128.
3390   if (DstTy == LLT::scalar(128)) {
3391     if (SrcTy.getSizeInBits() != 64)
3392       return false;
3393     MachineIRBuilder MIB(I);
3394     Register DstReg = I.getOperand(0).getReg();
3395     Register Src1Reg = I.getOperand(1).getReg();
3396     Register Src2Reg = I.getOperand(2).getReg();
3397     auto Tmp = MIB.buildInstr(TargetOpcode::IMPLICIT_DEF, {DstTy}, {});
3398     MachineInstr *InsMI =
3399         emitLaneInsert(None, Tmp.getReg(0), Src1Reg, /* LaneIdx */ 0, RB, MIB);
3400     if (!InsMI)
3401       return false;
3402     MachineInstr *Ins2MI = emitLaneInsert(DstReg, InsMI->getOperand(0).getReg(),
3403                                           Src2Reg, /* LaneIdx */ 1, RB, MIB);
3404     if (!Ins2MI)
3405       return false;
3406     constrainSelectedInstRegOperands(*InsMI, TII, TRI, RBI);
3407     constrainSelectedInstRegOperands(*Ins2MI, TII, TRI, RBI);
3408     I.eraseFromParent();
3409     return true;
3410   }
3411 
3412   if (RB.getID() != AArch64::GPRRegBankID)
3413     return false;
3414 
3415   if (DstTy.getSizeInBits() != 64 || SrcTy.getSizeInBits() != 32)
3416     return false;
3417 
3418   auto *DstRC = &AArch64::GPR64RegClass;
3419   Register SubToRegDef = MRI.createVirtualRegister(DstRC);
3420   MachineInstr &SubRegMI = *BuildMI(*I.getParent(), I, I.getDebugLoc(),
3421                                     TII.get(TargetOpcode::SUBREG_TO_REG))
3422                                 .addDef(SubToRegDef)
3423                                 .addImm(0)
3424                                 .addUse(I.getOperand(1).getReg())
3425                                 .addImm(AArch64::sub_32);
3426   Register SubToRegDef2 = MRI.createVirtualRegister(DstRC);
3427   // Need to anyext the second scalar before we can use bfm
3428   MachineInstr &SubRegMI2 = *BuildMI(*I.getParent(), I, I.getDebugLoc(),
3429                                     TII.get(TargetOpcode::SUBREG_TO_REG))
3430                                 .addDef(SubToRegDef2)
3431                                 .addImm(0)
3432                                 .addUse(I.getOperand(2).getReg())
3433                                 .addImm(AArch64::sub_32);
3434   MachineInstr &BFM =
3435       *BuildMI(*I.getParent(), I, I.getDebugLoc(), TII.get(AArch64::BFMXri))
3436            .addDef(I.getOperand(0).getReg())
3437            .addUse(SubToRegDef)
3438            .addUse(SubToRegDef2)
3439            .addImm(32)
3440            .addImm(31);
3441   constrainSelectedInstRegOperands(SubRegMI, TII, TRI, RBI);
3442   constrainSelectedInstRegOperands(SubRegMI2, TII, TRI, RBI);
3443   constrainSelectedInstRegOperands(BFM, TII, TRI, RBI);
3444   I.eraseFromParent();
3445   return true;
3446 }
3447 
3448 static bool getLaneCopyOpcode(unsigned &CopyOpc, unsigned &ExtractSubReg,
3449                               const unsigned EltSize) {
3450   // Choose a lane copy opcode and subregister based off of the size of the
3451   // vector's elements.
3452   switch (EltSize) {
3453   case 16:
3454     CopyOpc = AArch64::CPYi16;
3455     ExtractSubReg = AArch64::hsub;
3456     break;
3457   case 32:
3458     CopyOpc = AArch64::CPYi32;
3459     ExtractSubReg = AArch64::ssub;
3460     break;
3461   case 64:
3462     CopyOpc = AArch64::CPYi64;
3463     ExtractSubReg = AArch64::dsub;
3464     break;
3465   default:
3466     // Unknown size, bail out.
3467     LLVM_DEBUG(dbgs() << "Elt size '" << EltSize << "' unsupported.\n");
3468     return false;
3469   }
3470   return true;
3471 }
3472 
3473 MachineInstr *AArch64InstructionSelector::emitExtractVectorElt(
3474     Optional<Register> DstReg, const RegisterBank &DstRB, LLT ScalarTy,
3475     Register VecReg, unsigned LaneIdx, MachineIRBuilder &MIRBuilder) const {
3476   MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
3477   unsigned CopyOpc = 0;
3478   unsigned ExtractSubReg = 0;
3479   if (!getLaneCopyOpcode(CopyOpc, ExtractSubReg, ScalarTy.getSizeInBits())) {
3480     LLVM_DEBUG(
3481         dbgs() << "Couldn't determine lane copy opcode for instruction.\n");
3482     return nullptr;
3483   }
3484 
3485   const TargetRegisterClass *DstRC =
3486       getRegClassForTypeOnBank(ScalarTy, DstRB, RBI, true);
3487   if (!DstRC) {
3488     LLVM_DEBUG(dbgs() << "Could not determine destination register class.\n");
3489     return nullptr;
3490   }
3491 
3492   const RegisterBank &VecRB = *RBI.getRegBank(VecReg, MRI, TRI);
3493   const LLT &VecTy = MRI.getType(VecReg);
3494   const TargetRegisterClass *VecRC =
3495       getRegClassForTypeOnBank(VecTy, VecRB, RBI, true);
3496   if (!VecRC) {
3497     LLVM_DEBUG(dbgs() << "Could not determine source register class.\n");
3498     return nullptr;
3499   }
3500 
3501   // The register that we're going to copy into.
3502   Register InsertReg = VecReg;
3503   if (!DstReg)
3504     DstReg = MRI.createVirtualRegister(DstRC);
3505   // If the lane index is 0, we just use a subregister COPY.
3506   if (LaneIdx == 0) {
3507     auto Copy = MIRBuilder.buildInstr(TargetOpcode::COPY, {*DstReg}, {})
3508                     .addReg(VecReg, 0, ExtractSubReg);
3509     RBI.constrainGenericRegister(*DstReg, *DstRC, MRI);
3510     return &*Copy;
3511   }
3512 
3513   // Lane copies require 128-bit wide registers. If we're dealing with an
3514   // unpacked vector, then we need to move up to that width. Insert an implicit
3515   // def and a subregister insert to get us there.
3516   if (VecTy.getSizeInBits() != 128) {
3517     MachineInstr *ScalarToVector = emitScalarToVector(
3518         VecTy.getSizeInBits(), &AArch64::FPR128RegClass, VecReg, MIRBuilder);
3519     if (!ScalarToVector)
3520       return nullptr;
3521     InsertReg = ScalarToVector->getOperand(0).getReg();
3522   }
3523 
3524   MachineInstr *LaneCopyMI =
3525       MIRBuilder.buildInstr(CopyOpc, {*DstReg}, {InsertReg}).addImm(LaneIdx);
3526   constrainSelectedInstRegOperands(*LaneCopyMI, TII, TRI, RBI);
3527 
3528   // Make sure that we actually constrain the initial copy.
3529   RBI.constrainGenericRegister(*DstReg, *DstRC, MRI);
3530   return LaneCopyMI;
3531 }
3532 
3533 bool AArch64InstructionSelector::selectExtractElt(
3534     MachineInstr &I, MachineRegisterInfo &MRI) const {
3535   assert(I.getOpcode() == TargetOpcode::G_EXTRACT_VECTOR_ELT &&
3536          "unexpected opcode!");
3537   Register DstReg = I.getOperand(0).getReg();
3538   const LLT NarrowTy = MRI.getType(DstReg);
3539   const Register SrcReg = I.getOperand(1).getReg();
3540   const LLT WideTy = MRI.getType(SrcReg);
3541   (void)WideTy;
3542   assert(WideTy.getSizeInBits() >= NarrowTy.getSizeInBits() &&
3543          "source register size too small!");
3544   assert(NarrowTy.isScalar() && "cannot extract vector into vector!");
3545 
3546   // Need the lane index to determine the correct copy opcode.
3547   MachineOperand &LaneIdxOp = I.getOperand(2);
3548   assert(LaneIdxOp.isReg() && "Lane index operand was not a register?");
3549 
3550   if (RBI.getRegBank(DstReg, MRI, TRI)->getID() != AArch64::FPRRegBankID) {
3551     LLVM_DEBUG(dbgs() << "Cannot extract into GPR.\n");
3552     return false;
3553   }
3554 
3555   // Find the index to extract from.
3556   auto VRegAndVal = getConstantVRegValWithLookThrough(LaneIdxOp.getReg(), MRI);
3557   if (!VRegAndVal)
3558     return false;
3559   unsigned LaneIdx = VRegAndVal->Value;
3560 
3561   MachineIRBuilder MIRBuilder(I);
3562 
3563   const RegisterBank &DstRB = *RBI.getRegBank(DstReg, MRI, TRI);
3564   MachineInstr *Extract = emitExtractVectorElt(DstReg, DstRB, NarrowTy, SrcReg,
3565                                                LaneIdx, MIRBuilder);
3566   if (!Extract)
3567     return false;
3568 
3569   I.eraseFromParent();
3570   return true;
3571 }
3572 
3573 bool AArch64InstructionSelector::selectSplitVectorUnmerge(
3574     MachineInstr &I, MachineRegisterInfo &MRI) const {
3575   unsigned NumElts = I.getNumOperands() - 1;
3576   Register SrcReg = I.getOperand(NumElts).getReg();
3577   const LLT NarrowTy = MRI.getType(I.getOperand(0).getReg());
3578   const LLT SrcTy = MRI.getType(SrcReg);
3579 
3580   assert(NarrowTy.isVector() && "Expected an unmerge into vectors");
3581   if (SrcTy.getSizeInBits() > 128) {
3582     LLVM_DEBUG(dbgs() << "Unexpected vector type for vec split unmerge");
3583     return false;
3584   }
3585 
3586   MachineIRBuilder MIB(I);
3587 
3588   // We implement a split vector operation by treating the sub-vectors as
3589   // scalars and extracting them.
3590   const RegisterBank &DstRB =
3591       *RBI.getRegBank(I.getOperand(0).getReg(), MRI, TRI);
3592   for (unsigned OpIdx = 0; OpIdx < NumElts; ++OpIdx) {
3593     Register Dst = I.getOperand(OpIdx).getReg();
3594     MachineInstr *Extract =
3595         emitExtractVectorElt(Dst, DstRB, NarrowTy, SrcReg, OpIdx, MIB);
3596     if (!Extract)
3597       return false;
3598   }
3599   I.eraseFromParent();
3600   return true;
3601 }
3602 
3603 bool AArch64InstructionSelector::selectUnmergeValues(
3604     MachineInstr &I, MachineRegisterInfo &MRI) const {
3605   assert(I.getOpcode() == TargetOpcode::G_UNMERGE_VALUES &&
3606          "unexpected opcode");
3607 
3608   // TODO: Handle unmerging into GPRs and from scalars to scalars.
3609   if (RBI.getRegBank(I.getOperand(0).getReg(), MRI, TRI)->getID() !=
3610           AArch64::FPRRegBankID ||
3611       RBI.getRegBank(I.getOperand(1).getReg(), MRI, TRI)->getID() !=
3612           AArch64::FPRRegBankID) {
3613     LLVM_DEBUG(dbgs() << "Unmerging vector-to-gpr and scalar-to-scalar "
3614                          "currently unsupported.\n");
3615     return false;
3616   }
3617 
3618   // The last operand is the vector source register, and every other operand is
3619   // a register to unpack into.
3620   unsigned NumElts = I.getNumOperands() - 1;
3621   Register SrcReg = I.getOperand(NumElts).getReg();
3622   const LLT NarrowTy = MRI.getType(I.getOperand(0).getReg());
3623   const LLT WideTy = MRI.getType(SrcReg);
3624   (void)WideTy;
3625   assert((WideTy.isVector() || WideTy.getSizeInBits() == 128) &&
3626          "can only unmerge from vector or s128 types!");
3627   assert(WideTy.getSizeInBits() > NarrowTy.getSizeInBits() &&
3628          "source register size too small!");
3629 
3630   if (!NarrowTy.isScalar())
3631     return selectSplitVectorUnmerge(I, MRI);
3632 
3633   MachineIRBuilder MIB(I);
3634 
3635   // Choose a lane copy opcode and subregister based off of the size of the
3636   // vector's elements.
3637   unsigned CopyOpc = 0;
3638   unsigned ExtractSubReg = 0;
3639   if (!getLaneCopyOpcode(CopyOpc, ExtractSubReg, NarrowTy.getSizeInBits()))
3640     return false;
3641 
3642   // Set up for the lane copies.
3643   MachineBasicBlock &MBB = *I.getParent();
3644 
3645   // Stores the registers we'll be copying from.
3646   SmallVector<Register, 4> InsertRegs;
3647 
3648   // We'll use the first register twice, so we only need NumElts-1 registers.
3649   unsigned NumInsertRegs = NumElts - 1;
3650 
3651   // If our elements fit into exactly 128 bits, then we can copy from the source
3652   // directly. Otherwise, we need to do a bit of setup with some subregister
3653   // inserts.
3654   if (NarrowTy.getSizeInBits() * NumElts == 128) {
3655     InsertRegs = SmallVector<Register, 4>(NumInsertRegs, SrcReg);
3656   } else {
3657     // No. We have to perform subregister inserts. For each insert, create an
3658     // implicit def and a subregister insert, and save the register we create.
3659     for (unsigned Idx = 0; Idx < NumInsertRegs; ++Idx) {
3660       Register ImpDefReg = MRI.createVirtualRegister(&AArch64::FPR128RegClass);
3661       MachineInstr &ImpDefMI =
3662           *BuildMI(MBB, I, I.getDebugLoc(), TII.get(TargetOpcode::IMPLICIT_DEF),
3663                    ImpDefReg);
3664 
3665       // Now, create the subregister insert from SrcReg.
3666       Register InsertReg = MRI.createVirtualRegister(&AArch64::FPR128RegClass);
3667       MachineInstr &InsMI =
3668           *BuildMI(MBB, I, I.getDebugLoc(),
3669                    TII.get(TargetOpcode::INSERT_SUBREG), InsertReg)
3670                .addUse(ImpDefReg)
3671                .addUse(SrcReg)
3672                .addImm(AArch64::dsub);
3673 
3674       constrainSelectedInstRegOperands(ImpDefMI, TII, TRI, RBI);
3675       constrainSelectedInstRegOperands(InsMI, TII, TRI, RBI);
3676 
3677       // Save the register so that we can copy from it after.
3678       InsertRegs.push_back(InsertReg);
3679     }
3680   }
3681 
3682   // Now that we've created any necessary subregister inserts, we can
3683   // create the copies.
3684   //
3685   // Perform the first copy separately as a subregister copy.
3686   Register CopyTo = I.getOperand(0).getReg();
3687   auto FirstCopy = MIB.buildInstr(TargetOpcode::COPY, {CopyTo}, {})
3688                        .addReg(InsertRegs[0], 0, ExtractSubReg);
3689   constrainSelectedInstRegOperands(*FirstCopy, TII, TRI, RBI);
3690 
3691   // Now, perform the remaining copies as vector lane copies.
3692   unsigned LaneIdx = 1;
3693   for (Register InsReg : InsertRegs) {
3694     Register CopyTo = I.getOperand(LaneIdx).getReg();
3695     MachineInstr &CopyInst =
3696         *BuildMI(MBB, I, I.getDebugLoc(), TII.get(CopyOpc), CopyTo)
3697              .addUse(InsReg)
3698              .addImm(LaneIdx);
3699     constrainSelectedInstRegOperands(CopyInst, TII, TRI, RBI);
3700     ++LaneIdx;
3701   }
3702 
3703   // Separately constrain the first copy's destination. Because of the
3704   // limitation in constrainOperandRegClass, we can't guarantee that this will
3705   // actually be constrained. So, do it ourselves using the second operand.
3706   const TargetRegisterClass *RC =
3707       MRI.getRegClassOrNull(I.getOperand(1).getReg());
3708   if (!RC) {
3709     LLVM_DEBUG(dbgs() << "Couldn't constrain copy destination.\n");
3710     return false;
3711   }
3712 
3713   RBI.constrainGenericRegister(CopyTo, *RC, MRI);
3714   I.eraseFromParent();
3715   return true;
3716 }
3717 
3718 bool AArch64InstructionSelector::selectConcatVectors(
3719     MachineInstr &I, MachineRegisterInfo &MRI) const {
3720   assert(I.getOpcode() == TargetOpcode::G_CONCAT_VECTORS &&
3721          "Unexpected opcode");
3722   Register Dst = I.getOperand(0).getReg();
3723   Register Op1 = I.getOperand(1).getReg();
3724   Register Op2 = I.getOperand(2).getReg();
3725   MachineIRBuilder MIRBuilder(I);
3726   MachineInstr *ConcatMI = emitVectorConcat(Dst, Op1, Op2, MIRBuilder);
3727   if (!ConcatMI)
3728     return false;
3729   I.eraseFromParent();
3730   return true;
3731 }
3732 
3733 unsigned
3734 AArch64InstructionSelector::emitConstantPoolEntry(const Constant *CPVal,
3735                                                   MachineFunction &MF) const {
3736   Type *CPTy = CPVal->getType();
3737   Align Alignment = MF.getDataLayout().getPrefTypeAlign(CPTy);
3738 
3739   MachineConstantPool *MCP = MF.getConstantPool();
3740   return MCP->getConstantPoolIndex(CPVal, Alignment);
3741 }
3742 
3743 MachineInstr *AArch64InstructionSelector::emitLoadFromConstantPool(
3744     const Constant *CPVal, MachineIRBuilder &MIRBuilder) const {
3745   unsigned CPIdx = emitConstantPoolEntry(CPVal, MIRBuilder.getMF());
3746 
3747   auto Adrp =
3748       MIRBuilder.buildInstr(AArch64::ADRP, {&AArch64::GPR64RegClass}, {})
3749           .addConstantPoolIndex(CPIdx, 0, AArch64II::MO_PAGE);
3750 
3751   MachineInstr *LoadMI = nullptr;
3752   switch (MIRBuilder.getDataLayout().getTypeStoreSize(CPVal->getType())) {
3753   case 16:
3754     LoadMI =
3755         &*MIRBuilder
3756               .buildInstr(AArch64::LDRQui, {&AArch64::FPR128RegClass}, {Adrp})
3757               .addConstantPoolIndex(CPIdx, 0,
3758                                     AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3759     break;
3760   case 8:
3761     LoadMI = &*MIRBuilder
3762                  .buildInstr(AArch64::LDRDui, {&AArch64::FPR64RegClass}, {Adrp})
3763                  .addConstantPoolIndex(
3764                      CPIdx, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3765     break;
3766   default:
3767     LLVM_DEBUG(dbgs() << "Could not load from constant pool of type "
3768                       << *CPVal->getType());
3769     return nullptr;
3770   }
3771   constrainSelectedInstRegOperands(*Adrp, TII, TRI, RBI);
3772   constrainSelectedInstRegOperands(*LoadMI, TII, TRI, RBI);
3773   return LoadMI;
3774 }
3775 
3776 /// Return an <Opcode, SubregIndex> pair to do an vector elt insert of a given
3777 /// size and RB.
3778 static std::pair<unsigned, unsigned>
3779 getInsertVecEltOpInfo(const RegisterBank &RB, unsigned EltSize) {
3780   unsigned Opc, SubregIdx;
3781   if (RB.getID() == AArch64::GPRRegBankID) {
3782     if (EltSize == 16) {
3783       Opc = AArch64::INSvi16gpr;
3784       SubregIdx = AArch64::ssub;
3785     } else if (EltSize == 32) {
3786       Opc = AArch64::INSvi32gpr;
3787       SubregIdx = AArch64::ssub;
3788     } else if (EltSize == 64) {
3789       Opc = AArch64::INSvi64gpr;
3790       SubregIdx = AArch64::dsub;
3791     } else {
3792       llvm_unreachable("invalid elt size!");
3793     }
3794   } else {
3795     if (EltSize == 8) {
3796       Opc = AArch64::INSvi8lane;
3797       SubregIdx = AArch64::bsub;
3798     } else if (EltSize == 16) {
3799       Opc = AArch64::INSvi16lane;
3800       SubregIdx = AArch64::hsub;
3801     } else if (EltSize == 32) {
3802       Opc = AArch64::INSvi32lane;
3803       SubregIdx = AArch64::ssub;
3804     } else if (EltSize == 64) {
3805       Opc = AArch64::INSvi64lane;
3806       SubregIdx = AArch64::dsub;
3807     } else {
3808       llvm_unreachable("invalid elt size!");
3809     }
3810   }
3811   return std::make_pair(Opc, SubregIdx);
3812 }
3813 
3814 MachineInstr *AArch64InstructionSelector::emitInstr(
3815     unsigned Opcode, std::initializer_list<llvm::DstOp> DstOps,
3816     std::initializer_list<llvm::SrcOp> SrcOps, MachineIRBuilder &MIRBuilder,
3817     const ComplexRendererFns &RenderFns) const {
3818   assert(Opcode && "Expected an opcode?");
3819   assert(!isPreISelGenericOpcode(Opcode) &&
3820          "Function should only be used to produce selected instructions!");
3821   auto MI = MIRBuilder.buildInstr(Opcode, DstOps, SrcOps);
3822   if (RenderFns)
3823     for (auto &Fn : *RenderFns)
3824       Fn(MI);
3825   constrainSelectedInstRegOperands(*MI, TII, TRI, RBI);
3826   return &*MI;
3827 }
3828 
3829 MachineInstr *AArch64InstructionSelector::emitBinOp(
3830     const std::array<std::array<unsigned, 2>, 3> &AddrModeAndSizeToOpcode,
3831     Register Dst, MachineOperand &LHS, MachineOperand &RHS,
3832     MachineIRBuilder &MIRBuilder) const {
3833   MachineRegisterInfo &MRI = MIRBuilder.getMF().getRegInfo();
3834   assert(LHS.isReg() && RHS.isReg() && "Expected register operands?");
3835   auto Ty = MRI.getType(LHS.getReg());
3836   assert(!Ty.isVector() && "Expected a scalar or pointer?");
3837   unsigned Size = Ty.getSizeInBits();
3838   assert((Size == 32 || Size == 64) && "Expected a 32-bit or 64-bit type only");
3839   bool Is32Bit = Size == 32;
3840   if (auto Fns = selectArithImmed(RHS))
3841     return emitInstr(AddrModeAndSizeToOpcode[0][Is32Bit], {Dst}, {LHS},
3842                      MIRBuilder, Fns);
3843   if (auto Fns = selectShiftedRegister(RHS))
3844     return emitInstr(AddrModeAndSizeToOpcode[1][Is32Bit], {Dst}, {LHS},
3845                      MIRBuilder, Fns);
3846   return emitInstr(AddrModeAndSizeToOpcode[2][Is32Bit], {Dst}, {LHS, RHS},
3847                    MIRBuilder);
3848 }
3849 
3850 MachineInstr *
3851 AArch64InstructionSelector::emitADD(Register DefReg, MachineOperand &LHS,
3852                                     MachineOperand &RHS,
3853                                     MachineIRBuilder &MIRBuilder) const {
3854   const std::array<std::array<unsigned, 2>, 3> OpcTable{
3855       {{AArch64::ADDXri, AArch64::ADDWri},
3856        {AArch64::ADDXrs, AArch64::ADDWrs},
3857        {AArch64::ADDXrr, AArch64::ADDWrr}}};
3858   return emitBinOp(OpcTable, DefReg, LHS, RHS, MIRBuilder);
3859 }
3860 
3861 MachineInstr *
3862 AArch64InstructionSelector::emitADDS(Register Dst, MachineOperand &LHS,
3863                                      MachineOperand &RHS,
3864                                      MachineIRBuilder &MIRBuilder) const {
3865   const std::array<std::array<unsigned, 2>, 3> OpcTable{
3866       {{AArch64::ADDSXri, AArch64::ADDSWri},
3867        {AArch64::ADDSXrs, AArch64::ADDSWrs},
3868        {AArch64::ADDSXrr, AArch64::ADDSWrr}}};
3869   return emitBinOp(OpcTable, Dst, LHS, RHS, MIRBuilder);
3870 }
3871 
3872 MachineInstr *
3873 AArch64InstructionSelector::emitSUBS(Register Dst, MachineOperand &LHS,
3874                                      MachineOperand &RHS,
3875                                      MachineIRBuilder &MIRBuilder) const {
3876   const std::array<std::array<unsigned, 2>, 3> OpcTable{
3877       {{AArch64::SUBSXri, AArch64::SUBSWri},
3878        {AArch64::SUBSXrs, AArch64::SUBSWrs},
3879        {AArch64::SUBSXrr, AArch64::SUBSWrr}}};
3880   return emitBinOp(OpcTable, Dst, LHS, RHS, MIRBuilder);
3881 }
3882 
3883 MachineInstr *
3884 AArch64InstructionSelector::emitCMN(MachineOperand &LHS, MachineOperand &RHS,
3885                                     MachineIRBuilder &MIRBuilder) const {
3886   MachineRegisterInfo &MRI = MIRBuilder.getMF().getRegInfo();
3887   bool Is32Bit = (MRI.getType(LHS.getReg()).getSizeInBits() == 32);
3888   return emitADDS(Is32Bit ? AArch64::WZR : AArch64::XZR, LHS, RHS, MIRBuilder);
3889 }
3890 
3891 MachineInstr *
3892 AArch64InstructionSelector::emitTST(MachineOperand &LHS, MachineOperand &RHS,
3893                                     MachineIRBuilder &MIRBuilder) const {
3894   assert(LHS.isReg() && RHS.isReg() && "Expected register operands?");
3895   MachineRegisterInfo &MRI = MIRBuilder.getMF().getRegInfo();
3896   LLT Ty = MRI.getType(LHS.getReg());
3897   unsigned RegSize = Ty.getSizeInBits();
3898   bool Is32Bit = (RegSize == 32);
3899   const unsigned OpcTable[3][2] = {{AArch64::ANDSXri, AArch64::ANDSWri},
3900                                    {AArch64::ANDSXrs, AArch64::ANDSWrs},
3901                                    {AArch64::ANDSXrr, AArch64::ANDSWrr}};
3902   // ANDS needs a logical immediate for its immediate form. Check if we can
3903   // fold one in.
3904   if (auto ValAndVReg = getConstantVRegValWithLookThrough(RHS.getReg(), MRI)) {
3905     if (AArch64_AM::isLogicalImmediate(ValAndVReg->Value, RegSize)) {
3906       auto TstMI = MIRBuilder.buildInstr(OpcTable[0][Is32Bit], {Ty}, {LHS});
3907       TstMI.addImm(
3908           AArch64_AM::encodeLogicalImmediate(ValAndVReg->Value, RegSize));
3909       constrainSelectedInstRegOperands(*TstMI, TII, TRI, RBI);
3910       return &*TstMI;
3911     }
3912   }
3913 
3914   if (auto Fns = selectLogicalShiftedRegister(RHS))
3915     return emitInstr(OpcTable[1][Is32Bit], {Ty}, {LHS}, MIRBuilder, Fns);
3916   return emitInstr(OpcTable[2][Is32Bit], {Ty}, {LHS, RHS}, MIRBuilder);
3917 }
3918 
3919 MachineInstr *AArch64InstructionSelector::emitIntegerCompare(
3920     MachineOperand &LHS, MachineOperand &RHS, MachineOperand &Predicate,
3921     MachineIRBuilder &MIRBuilder) const {
3922   assert(LHS.isReg() && RHS.isReg() && "Expected LHS and RHS to be registers!");
3923   assert(Predicate.isPredicate() && "Expected predicate?");
3924   MachineRegisterInfo &MRI = MIRBuilder.getMF().getRegInfo();
3925   LLT CmpTy = MRI.getType(LHS.getReg());
3926   assert(!CmpTy.isVector() && "Expected scalar or pointer");
3927   unsigned Size = CmpTy.getSizeInBits();
3928   (void)Size;
3929   assert((Size == 32 || Size == 64) && "Expected a 32-bit or 64-bit LHS/RHS?");
3930   // Fold the compare into a cmn or tst if possible.
3931   if (auto FoldCmp = tryFoldIntegerCompare(LHS, RHS, Predicate, MIRBuilder))
3932     return FoldCmp;
3933   auto Dst = MRI.cloneVirtualRegister(LHS.getReg());
3934   return emitSUBS(Dst, LHS, RHS, MIRBuilder);
3935 }
3936 
3937 MachineInstr *AArch64InstructionSelector::emitCSetForFCmp(
3938     Register Dst, CmpInst::Predicate Pred, MachineIRBuilder &MIRBuilder) const {
3939   MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
3940 #ifndef NDEBUG
3941   LLT Ty = MRI.getType(Dst);
3942   assert(!Ty.isVector() && Ty.getSizeInBits() == 32 &&
3943          "Expected a 32-bit scalar register?");
3944 #endif
3945   const Register ZeroReg = AArch64::WZR;
3946   auto EmitCSet = [&](Register CsetDst, AArch64CC::CondCode CC) {
3947     auto CSet =
3948         MIRBuilder.buildInstr(AArch64::CSINCWr, {CsetDst}, {ZeroReg, ZeroReg})
3949             .addImm(getInvertedCondCode(CC));
3950     constrainSelectedInstRegOperands(*CSet, TII, TRI, RBI);
3951     return &*CSet;
3952   };
3953 
3954   AArch64CC::CondCode CC1, CC2;
3955   changeFCMPPredToAArch64CC(Pred, CC1, CC2);
3956   if (CC2 == AArch64CC::AL)
3957     return EmitCSet(Dst, CC1);
3958 
3959   const TargetRegisterClass *RC = &AArch64::GPR32RegClass;
3960   Register Def1Reg = MRI.createVirtualRegister(RC);
3961   Register Def2Reg = MRI.createVirtualRegister(RC);
3962   EmitCSet(Def1Reg, CC1);
3963   EmitCSet(Def2Reg, CC2);
3964   auto OrMI = MIRBuilder.buildInstr(AArch64::ORRWrr, {Dst}, {Def1Reg, Def2Reg});
3965   constrainSelectedInstRegOperands(*OrMI, TII, TRI, RBI);
3966   return &*OrMI;
3967 }
3968 
3969 MachineInstr *
3970 AArch64InstructionSelector::emitFPCompare(Register LHS, Register RHS,
3971                                           MachineIRBuilder &MIRBuilder) const {
3972   MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
3973   LLT Ty = MRI.getType(LHS);
3974   if (Ty.isVector())
3975     return nullptr;
3976   unsigned OpSize = Ty.getSizeInBits();
3977   if (OpSize != 32 && OpSize != 64)
3978     return nullptr;
3979 
3980   // If this is a compare against +0.0, then we don't have
3981   // to explicitly materialize a constant.
3982   const ConstantFP *FPImm = getConstantFPVRegVal(RHS, MRI);
3983   bool ShouldUseImm = FPImm && (FPImm->isZero() && !FPImm->isNegative());
3984   unsigned CmpOpcTbl[2][2] = {{AArch64::FCMPSrr, AArch64::FCMPDrr},
3985                               {AArch64::FCMPSri, AArch64::FCMPDri}};
3986   unsigned CmpOpc = CmpOpcTbl[ShouldUseImm][OpSize == 64];
3987 
3988   // Partially build the compare. Decide if we need to add a use for the
3989   // third operand based off whether or not we're comparing against 0.0.
3990   auto CmpMI = MIRBuilder.buildInstr(CmpOpc).addUse(LHS);
3991   if (!ShouldUseImm)
3992     CmpMI.addUse(RHS);
3993   constrainSelectedInstRegOperands(*CmpMI, TII, TRI, RBI);
3994   return &*CmpMI;
3995 }
3996 
3997 MachineInstr *AArch64InstructionSelector::emitVectorConcat(
3998     Optional<Register> Dst, Register Op1, Register Op2,
3999     MachineIRBuilder &MIRBuilder) const {
4000   // We implement a vector concat by:
4001   // 1. Use scalar_to_vector to insert the lower vector into the larger dest
4002   // 2. Insert the upper vector into the destination's upper element
4003   // TODO: some of this code is common with G_BUILD_VECTOR handling.
4004   MachineRegisterInfo &MRI = MIRBuilder.getMF().getRegInfo();
4005 
4006   const LLT Op1Ty = MRI.getType(Op1);
4007   const LLT Op2Ty = MRI.getType(Op2);
4008 
4009   if (Op1Ty != Op2Ty) {
4010     LLVM_DEBUG(dbgs() << "Could not do vector concat of differing vector tys");
4011     return nullptr;
4012   }
4013   assert(Op1Ty.isVector() && "Expected a vector for vector concat");
4014 
4015   if (Op1Ty.getSizeInBits() >= 128) {
4016     LLVM_DEBUG(dbgs() << "Vector concat not supported for full size vectors");
4017     return nullptr;
4018   }
4019 
4020   // At the moment we just support 64 bit vector concats.
4021   if (Op1Ty.getSizeInBits() != 64) {
4022     LLVM_DEBUG(dbgs() << "Vector concat supported for 64b vectors");
4023     return nullptr;
4024   }
4025 
4026   const LLT ScalarTy = LLT::scalar(Op1Ty.getSizeInBits());
4027   const RegisterBank &FPRBank = *RBI.getRegBank(Op1, MRI, TRI);
4028   const TargetRegisterClass *DstRC =
4029       getMinClassForRegBank(FPRBank, Op1Ty.getSizeInBits() * 2);
4030 
4031   MachineInstr *WidenedOp1 =
4032       emitScalarToVector(ScalarTy.getSizeInBits(), DstRC, Op1, MIRBuilder);
4033   MachineInstr *WidenedOp2 =
4034       emitScalarToVector(ScalarTy.getSizeInBits(), DstRC, Op2, MIRBuilder);
4035   if (!WidenedOp1 || !WidenedOp2) {
4036     LLVM_DEBUG(dbgs() << "Could not emit a vector from scalar value");
4037     return nullptr;
4038   }
4039 
4040   // Now do the insert of the upper element.
4041   unsigned InsertOpc, InsSubRegIdx;
4042   std::tie(InsertOpc, InsSubRegIdx) =
4043       getInsertVecEltOpInfo(FPRBank, ScalarTy.getSizeInBits());
4044 
4045   if (!Dst)
4046     Dst = MRI.createVirtualRegister(DstRC);
4047   auto InsElt =
4048       MIRBuilder
4049           .buildInstr(InsertOpc, {*Dst}, {WidenedOp1->getOperand(0).getReg()})
4050           .addImm(1) /* Lane index */
4051           .addUse(WidenedOp2->getOperand(0).getReg())
4052           .addImm(0);
4053   constrainSelectedInstRegOperands(*InsElt, TII, TRI, RBI);
4054   return &*InsElt;
4055 }
4056 
4057 MachineInstr *AArch64InstructionSelector::emitFMovForFConstant(
4058     MachineInstr &I, MachineRegisterInfo &MRI) const {
4059   assert(I.getOpcode() == TargetOpcode::G_FCONSTANT &&
4060          "Expected a G_FCONSTANT!");
4061   MachineOperand &ImmOp = I.getOperand(1);
4062   unsigned DefSize = MRI.getType(I.getOperand(0).getReg()).getSizeInBits();
4063 
4064   // Only handle 32 and 64 bit defs for now.
4065   if (DefSize != 32 && DefSize != 64)
4066     return nullptr;
4067 
4068   // Don't handle null values using FMOV.
4069   if (ImmOp.getFPImm()->isNullValue())
4070     return nullptr;
4071 
4072   // Get the immediate representation for the FMOV.
4073   const APFloat &ImmValAPF = ImmOp.getFPImm()->getValueAPF();
4074   int Imm = DefSize == 32 ? AArch64_AM::getFP32Imm(ImmValAPF)
4075                           : AArch64_AM::getFP64Imm(ImmValAPF);
4076 
4077   // If this is -1, it means the immediate can't be represented as the requested
4078   // floating point value. Bail.
4079   if (Imm == -1)
4080     return nullptr;
4081 
4082   // Update MI to represent the new FMOV instruction, constrain it, and return.
4083   ImmOp.ChangeToImmediate(Imm);
4084   unsigned MovOpc = DefSize == 32 ? AArch64::FMOVSi : AArch64::FMOVDi;
4085   I.setDesc(TII.get(MovOpc));
4086   constrainSelectedInstRegOperands(I, TII, TRI, RBI);
4087   return &I;
4088 }
4089 
4090 MachineInstr *
4091 AArch64InstructionSelector::emitCSetForICMP(Register DefReg, unsigned Pred,
4092                                      MachineIRBuilder &MIRBuilder) const {
4093   // CSINC increments the result when the predicate is false. Invert it.
4094   const AArch64CC::CondCode InvCC = changeICMPPredToAArch64CC(
4095       CmpInst::getInversePredicate((CmpInst::Predicate)Pred));
4096   auto I =
4097       MIRBuilder
4098     .buildInstr(AArch64::CSINCWr, {DefReg}, {Register(AArch64::WZR), Register(AArch64::WZR)})
4099           .addImm(InvCC);
4100   constrainSelectedInstRegOperands(*I, TII, TRI, RBI);
4101   return &*I;
4102 }
4103 
4104 bool AArch64InstructionSelector::tryOptSelect(MachineInstr &I) const {
4105   MachineIRBuilder MIB(I);
4106   MachineRegisterInfo &MRI = *MIB.getMRI();
4107   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
4108   Register SrcReg1 = I.getOperand(2).getReg();
4109   Register SrcReg2 = I.getOperand(3).getReg();
4110   // We want to recognize this pattern:
4111   //
4112   // $z = G_FCMP pred, $x, $y
4113   // ...
4114   // $w = G_SELECT $z, $a, $b
4115   //
4116   // Where the value of $z is *only* ever used by the G_SELECT (possibly with
4117   // some copies/truncs in between.)
4118   //
4119   // If we see this, then we can emit something like this:
4120   //
4121   // fcmp $x, $y
4122   // fcsel $w, $a, $b, pred
4123   //
4124   // Rather than emitting both of the rather long sequences in the standard
4125   // G_FCMP/G_SELECT select methods.
4126 
4127   // First, check if the condition is defined by a compare.
4128   MachineInstr *CondDef = MRI.getVRegDef(I.getOperand(1).getReg());
4129   while (CondDef) {
4130     // We can only fold if all of the defs have one use.
4131     Register CondDefReg = CondDef->getOperand(0).getReg();
4132     if (!MRI.hasOneNonDBGUse(CondDefReg)) {
4133       // Unless it's another select.
4134       for (const MachineInstr &UI : MRI.use_nodbg_instructions(CondDefReg)) {
4135         if (CondDef == &UI)
4136           continue;
4137         if (UI.getOpcode() != TargetOpcode::G_SELECT)
4138           return false;
4139       }
4140     }
4141 
4142     // We can skip over G_TRUNC since the condition is 1-bit.
4143     // Truncating/extending can have no impact on the value.
4144     unsigned Opc = CondDef->getOpcode();
4145     if (Opc != TargetOpcode::COPY && Opc != TargetOpcode::G_TRUNC)
4146       break;
4147 
4148     // Can't see past copies from physregs.
4149     if (Opc == TargetOpcode::COPY &&
4150         Register::isPhysicalRegister(CondDef->getOperand(1).getReg()))
4151       return false;
4152 
4153     CondDef = MRI.getVRegDef(CondDef->getOperand(1).getReg());
4154   }
4155 
4156   // Is the condition defined by a compare?
4157   if (!CondDef)
4158     return false;
4159 
4160   unsigned CondOpc = CondDef->getOpcode();
4161   if (CondOpc != TargetOpcode::G_ICMP && CondOpc != TargetOpcode::G_FCMP)
4162     return false;
4163 
4164   AArch64CC::CondCode CondCode;
4165   if (CondOpc == TargetOpcode::G_ICMP) {
4166     auto Pred =
4167         static_cast<CmpInst::Predicate>(CondDef->getOperand(1).getPredicate());
4168     CondCode = changeICMPPredToAArch64CC(Pred);
4169     emitIntegerCompare(CondDef->getOperand(2), CondDef->getOperand(3),
4170                        CondDef->getOperand(1), MIB);
4171   } else {
4172     // Get the condition code for the select.
4173     auto Pred =
4174         static_cast<CmpInst::Predicate>(CondDef->getOperand(1).getPredicate());
4175     AArch64CC::CondCode CondCode2;
4176     changeFCMPPredToAArch64CC(Pred, CondCode, CondCode2);
4177 
4178     // changeFCMPPredToAArch64CC sets CondCode2 to AL when we require two
4179     // instructions to emit the comparison.
4180     // TODO: Handle FCMP_UEQ and FCMP_ONE. After that, this check will be
4181     // unnecessary.
4182     if (CondCode2 != AArch64CC::AL)
4183       return false;
4184 
4185     if (!emitFPCompare(CondDef->getOperand(2).getReg(),
4186                        CondDef->getOperand(3).getReg(), MIB)) {
4187       LLVM_DEBUG(dbgs() << "Couldn't emit compare for select!\n");
4188       return false;
4189     }
4190   }
4191 
4192   // Emit the select.
4193   // We may also be able to emit a CSINC if the RHS operand is a 1.
4194   const RegisterBank &SrcRB = *RBI.getRegBank(SrcReg1, MRI, TRI);
4195   auto ValAndVReg =
4196       getConstantVRegValWithLookThrough(SrcReg2, MRI);
4197 
4198   if (SrcRB.getID() == AArch64::GPRRegBankID && ValAndVReg &&
4199       ValAndVReg->Value == 1) {
4200     unsigned Size = MRI.getType(SrcReg1).getSizeInBits();
4201     unsigned Opc = 0;
4202     Register Zero;
4203     if (Size == 64) {
4204       Opc = AArch64::CSINCXr;
4205       Zero = AArch64::XZR;
4206     } else {
4207       Opc = AArch64::CSINCWr;
4208       Zero = AArch64::WZR;
4209     }
4210     auto CSINC =
4211         MIB.buildInstr(Opc, {I.getOperand(0).getReg()}, {SrcReg1, Zero})
4212             .addImm(CondCode);
4213     constrainSelectedInstRegOperands(*CSINC, TII, TRI, RBI);
4214     I.eraseFromParent();
4215     return true;
4216   }
4217 
4218   unsigned CSelOpc = selectSelectOpc(I, MRI, RBI);
4219   auto CSel =
4220       MIB.buildInstr(CSelOpc, {I.getOperand(0).getReg()},
4221                      {I.getOperand(2).getReg(), I.getOperand(3).getReg()})
4222           .addImm(CondCode);
4223   constrainSelectedInstRegOperands(*CSel, TII, TRI, RBI);
4224   I.eraseFromParent();
4225   return true;
4226 }
4227 
4228 MachineInstr *AArch64InstructionSelector::tryFoldIntegerCompare(
4229     MachineOperand &LHS, MachineOperand &RHS, MachineOperand &Predicate,
4230     MachineIRBuilder &MIRBuilder) const {
4231   assert(LHS.isReg() && RHS.isReg() && Predicate.isPredicate() &&
4232          "Unexpected MachineOperand");
4233   MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
4234   // We want to find this sort of thing:
4235   // x = G_SUB 0, y
4236   // G_ICMP z, x
4237   //
4238   // In this case, we can fold the G_SUB into the G_ICMP using a CMN instead.
4239   // e.g:
4240   //
4241   // cmn z, y
4242 
4243   // Helper lambda to detect the subtract followed by the compare.
4244   // Takes in the def of the LHS or RHS, and checks if it's a subtract from 0.
4245   auto IsCMN = [&](MachineInstr *DefMI, const AArch64CC::CondCode &CC) {
4246     if (!DefMI || DefMI->getOpcode() != TargetOpcode::G_SUB)
4247       return false;
4248 
4249     // Need to make sure NZCV is the same at the end of the transformation.
4250     if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
4251       return false;
4252 
4253     // We want to match against SUBs.
4254     if (DefMI->getOpcode() != TargetOpcode::G_SUB)
4255       return false;
4256 
4257     // Make sure that we're getting
4258     // x = G_SUB 0, y
4259     auto ValAndVReg =
4260         getConstantVRegValWithLookThrough(DefMI->getOperand(1).getReg(), MRI);
4261     if (!ValAndVReg || ValAndVReg->Value != 0)
4262       return false;
4263 
4264     // This can safely be represented as a CMN.
4265     return true;
4266   };
4267 
4268   // Check if the RHS or LHS of the G_ICMP is defined by a SUB
4269   MachineInstr *LHSDef = getDefIgnoringCopies(LHS.getReg(), MRI);
4270   MachineInstr *RHSDef = getDefIgnoringCopies(RHS.getReg(), MRI);
4271   CmpInst::Predicate P = (CmpInst::Predicate)Predicate.getPredicate();
4272   const AArch64CC::CondCode CC = changeICMPPredToAArch64CC(P);
4273 
4274   // Given this:
4275   //
4276   // x = G_SUB 0, y
4277   // G_ICMP x, z
4278   //
4279   // Produce this:
4280   //
4281   // cmn y, z
4282   if (IsCMN(LHSDef, CC))
4283     return emitCMN(LHSDef->getOperand(2), RHS, MIRBuilder);
4284 
4285   // Same idea here, but with the RHS of the compare instead:
4286   //
4287   // Given this:
4288   //
4289   // x = G_SUB 0, y
4290   // G_ICMP z, x
4291   //
4292   // Produce this:
4293   //
4294   // cmn z, y
4295   if (IsCMN(RHSDef, CC))
4296     return emitCMN(LHS, RHSDef->getOperand(2), MIRBuilder);
4297 
4298   // Given this:
4299   //
4300   // z = G_AND x, y
4301   // G_ICMP z, 0
4302   //
4303   // Produce this if the compare is signed:
4304   //
4305   // tst x, y
4306   if (!isUnsignedICMPPred(P) && LHSDef &&
4307       LHSDef->getOpcode() == TargetOpcode::G_AND) {
4308     // Make sure that the RHS is 0.
4309     auto ValAndVReg = getConstantVRegValWithLookThrough(RHS.getReg(), MRI);
4310     if (!ValAndVReg || ValAndVReg->Value != 0)
4311       return nullptr;
4312 
4313     return emitTST(LHSDef->getOperand(1),
4314                    LHSDef->getOperand(2), MIRBuilder);
4315   }
4316 
4317   return nullptr;
4318 }
4319 
4320 bool AArch64InstructionSelector::selectShuffleVector(
4321     MachineInstr &I, MachineRegisterInfo &MRI) const {
4322   const LLT DstTy = MRI.getType(I.getOperand(0).getReg());
4323   Register Src1Reg = I.getOperand(1).getReg();
4324   const LLT Src1Ty = MRI.getType(Src1Reg);
4325   Register Src2Reg = I.getOperand(2).getReg();
4326   const LLT Src2Ty = MRI.getType(Src2Reg);
4327   ArrayRef<int> Mask = I.getOperand(3).getShuffleMask();
4328 
4329   MachineBasicBlock &MBB = *I.getParent();
4330   MachineFunction &MF = *MBB.getParent();
4331   LLVMContext &Ctx = MF.getFunction().getContext();
4332 
4333   // G_SHUFFLE_VECTOR is weird in that the source operands can be scalars, if
4334   // it's originated from a <1 x T> type. Those should have been lowered into
4335   // G_BUILD_VECTOR earlier.
4336   if (!Src1Ty.isVector() || !Src2Ty.isVector()) {
4337     LLVM_DEBUG(dbgs() << "Could not select a \"scalar\" G_SHUFFLE_VECTOR\n");
4338     return false;
4339   }
4340 
4341   unsigned BytesPerElt = DstTy.getElementType().getSizeInBits() / 8;
4342 
4343   SmallVector<Constant *, 64> CstIdxs;
4344   for (int Val : Mask) {
4345     // For now, any undef indexes we'll just assume to be 0. This should be
4346     // optimized in future, e.g. to select DUP etc.
4347     Val = Val < 0 ? 0 : Val;
4348     for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
4349       unsigned Offset = Byte + Val * BytesPerElt;
4350       CstIdxs.emplace_back(ConstantInt::get(Type::getInt8Ty(Ctx), Offset));
4351     }
4352   }
4353 
4354   MachineIRBuilder MIRBuilder(I);
4355 
4356   // Use a constant pool to load the index vector for TBL.
4357   Constant *CPVal = ConstantVector::get(CstIdxs);
4358   MachineInstr *IndexLoad = emitLoadFromConstantPool(CPVal, MIRBuilder);
4359   if (!IndexLoad) {
4360     LLVM_DEBUG(dbgs() << "Could not load from a constant pool");
4361     return false;
4362   }
4363 
4364   if (DstTy.getSizeInBits() != 128) {
4365     assert(DstTy.getSizeInBits() == 64 && "Unexpected shuffle result ty");
4366     // This case can be done with TBL1.
4367     MachineInstr *Concat = emitVectorConcat(None, Src1Reg, Src2Reg, MIRBuilder);
4368     if (!Concat) {
4369       LLVM_DEBUG(dbgs() << "Could not do vector concat for tbl1");
4370       return false;
4371     }
4372 
4373     // The constant pool load will be 64 bits, so need to convert to FPR128 reg.
4374     IndexLoad =
4375         emitScalarToVector(64, &AArch64::FPR128RegClass,
4376                            IndexLoad->getOperand(0).getReg(), MIRBuilder);
4377 
4378     auto TBL1 = MIRBuilder.buildInstr(
4379         AArch64::TBLv16i8One, {&AArch64::FPR128RegClass},
4380         {Concat->getOperand(0).getReg(), IndexLoad->getOperand(0).getReg()});
4381     constrainSelectedInstRegOperands(*TBL1, TII, TRI, RBI);
4382 
4383     auto Copy =
4384         MIRBuilder
4385             .buildInstr(TargetOpcode::COPY, {I.getOperand(0).getReg()}, {})
4386             .addReg(TBL1.getReg(0), 0, AArch64::dsub);
4387     RBI.constrainGenericRegister(Copy.getReg(0), AArch64::FPR64RegClass, MRI);
4388     I.eraseFromParent();
4389     return true;
4390   }
4391 
4392   // For TBL2 we need to emit a REG_SEQUENCE to tie together two consecutive
4393   // Q registers for regalloc.
4394   auto RegSeq = MIRBuilder
4395                     .buildInstr(TargetOpcode::REG_SEQUENCE,
4396                                 {&AArch64::QQRegClass}, {Src1Reg})
4397                     .addImm(AArch64::qsub0)
4398                     .addUse(Src2Reg)
4399                     .addImm(AArch64::qsub1);
4400 
4401   auto TBL2 = MIRBuilder.buildInstr(AArch64::TBLv16i8Two, {I.getOperand(0)},
4402                                     {RegSeq, IndexLoad->getOperand(0)});
4403   constrainSelectedInstRegOperands(*RegSeq, TII, TRI, RBI);
4404   constrainSelectedInstRegOperands(*TBL2, TII, TRI, RBI);
4405   I.eraseFromParent();
4406   return true;
4407 }
4408 
4409 MachineInstr *AArch64InstructionSelector::emitLaneInsert(
4410     Optional<Register> DstReg, Register SrcReg, Register EltReg,
4411     unsigned LaneIdx, const RegisterBank &RB,
4412     MachineIRBuilder &MIRBuilder) const {
4413   MachineInstr *InsElt = nullptr;
4414   const TargetRegisterClass *DstRC = &AArch64::FPR128RegClass;
4415   MachineRegisterInfo &MRI = *MIRBuilder.getMRI();
4416 
4417   // Create a register to define with the insert if one wasn't passed in.
4418   if (!DstReg)
4419     DstReg = MRI.createVirtualRegister(DstRC);
4420 
4421   unsigned EltSize = MRI.getType(EltReg).getSizeInBits();
4422   unsigned Opc = getInsertVecEltOpInfo(RB, EltSize).first;
4423 
4424   if (RB.getID() == AArch64::FPRRegBankID) {
4425     auto InsSub = emitScalarToVector(EltSize, DstRC, EltReg, MIRBuilder);
4426     InsElt = MIRBuilder.buildInstr(Opc, {*DstReg}, {SrcReg})
4427                  .addImm(LaneIdx)
4428                  .addUse(InsSub->getOperand(0).getReg())
4429                  .addImm(0);
4430   } else {
4431     InsElt = MIRBuilder.buildInstr(Opc, {*DstReg}, {SrcReg})
4432                  .addImm(LaneIdx)
4433                  .addUse(EltReg);
4434   }
4435 
4436   constrainSelectedInstRegOperands(*InsElt, TII, TRI, RBI);
4437   return InsElt;
4438 }
4439 
4440 bool AArch64InstructionSelector::selectInsertElt(
4441     MachineInstr &I, MachineRegisterInfo &MRI) const {
4442   assert(I.getOpcode() == TargetOpcode::G_INSERT_VECTOR_ELT);
4443 
4444   // Get information on the destination.
4445   Register DstReg = I.getOperand(0).getReg();
4446   const LLT DstTy = MRI.getType(DstReg);
4447   unsigned VecSize = DstTy.getSizeInBits();
4448 
4449   // Get information on the element we want to insert into the destination.
4450   Register EltReg = I.getOperand(2).getReg();
4451   const LLT EltTy = MRI.getType(EltReg);
4452   unsigned EltSize = EltTy.getSizeInBits();
4453   if (EltSize < 16 || EltSize > 64)
4454     return false; // Don't support all element types yet.
4455 
4456   // Find the definition of the index. Bail out if it's not defined by a
4457   // G_CONSTANT.
4458   Register IdxReg = I.getOperand(3).getReg();
4459   auto VRegAndVal = getConstantVRegValWithLookThrough(IdxReg, MRI);
4460   if (!VRegAndVal)
4461     return false;
4462   unsigned LaneIdx = VRegAndVal->Value;
4463 
4464   // Perform the lane insert.
4465   Register SrcReg = I.getOperand(1).getReg();
4466   const RegisterBank &EltRB = *RBI.getRegBank(EltReg, MRI, TRI);
4467   MachineIRBuilder MIRBuilder(I);
4468 
4469   if (VecSize < 128) {
4470     // If the vector we're inserting into is smaller than 128 bits, widen it
4471     // to 128 to do the insert.
4472     MachineInstr *ScalarToVec = emitScalarToVector(
4473         VecSize, &AArch64::FPR128RegClass, SrcReg, MIRBuilder);
4474     if (!ScalarToVec)
4475       return false;
4476     SrcReg = ScalarToVec->getOperand(0).getReg();
4477   }
4478 
4479   // Create an insert into a new FPR128 register.
4480   // Note that if our vector is already 128 bits, we end up emitting an extra
4481   // register.
4482   MachineInstr *InsMI =
4483       emitLaneInsert(None, SrcReg, EltReg, LaneIdx, EltRB, MIRBuilder);
4484 
4485   if (VecSize < 128) {
4486     // If we had to widen to perform the insert, then we have to demote back to
4487     // the original size to get the result we want.
4488     Register DemoteVec = InsMI->getOperand(0).getReg();
4489     const TargetRegisterClass *RC =
4490         getMinClassForRegBank(*RBI.getRegBank(DemoteVec, MRI, TRI), VecSize);
4491     if (RC != &AArch64::FPR32RegClass && RC != &AArch64::FPR64RegClass) {
4492       LLVM_DEBUG(dbgs() << "Unsupported register class!\n");
4493       return false;
4494     }
4495     unsigned SubReg = 0;
4496     if (!getSubRegForClass(RC, TRI, SubReg))
4497       return false;
4498     if (SubReg != AArch64::ssub && SubReg != AArch64::dsub) {
4499       LLVM_DEBUG(dbgs() << "Unsupported destination size! (" << VecSize
4500                         << "\n");
4501       return false;
4502     }
4503     MIRBuilder.buildInstr(TargetOpcode::COPY, {DstReg}, {})
4504         .addReg(DemoteVec, 0, SubReg);
4505     RBI.constrainGenericRegister(DstReg, *RC, MRI);
4506   } else {
4507     // No widening needed.
4508     InsMI->getOperand(0).setReg(DstReg);
4509     constrainSelectedInstRegOperands(*InsMI, TII, TRI, RBI);
4510   }
4511 
4512   I.eraseFromParent();
4513   return true;
4514 }
4515 
4516 bool AArch64InstructionSelector::tryOptConstantBuildVec(
4517     MachineInstr &I, LLT DstTy, MachineRegisterInfo &MRI) const {
4518   assert(I.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
4519   unsigned DstSize = DstTy.getSizeInBits();
4520   assert(DstSize <= 128 && "Unexpected build_vec type!");
4521   if (DstSize < 32)
4522     return false;
4523   // Check if we're building a constant vector, in which case we want to
4524   // generate a constant pool load instead of a vector insert sequence.
4525   SmallVector<Constant *, 16> Csts;
4526   for (unsigned Idx = 1; Idx < I.getNumOperands(); ++Idx) {
4527     // Try to find G_CONSTANT or G_FCONSTANT
4528     auto *OpMI =
4529         getOpcodeDef(TargetOpcode::G_CONSTANT, I.getOperand(Idx).getReg(), MRI);
4530     if (OpMI)
4531       Csts.emplace_back(
4532           const_cast<ConstantInt *>(OpMI->getOperand(1).getCImm()));
4533     else if ((OpMI = getOpcodeDef(TargetOpcode::G_FCONSTANT,
4534                                   I.getOperand(Idx).getReg(), MRI)))
4535       Csts.emplace_back(
4536           const_cast<ConstantFP *>(OpMI->getOperand(1).getFPImm()));
4537     else
4538       return false;
4539   }
4540   Constant *CV = ConstantVector::get(Csts);
4541   MachineIRBuilder MIB(I);
4542   if (CV->isNullValue()) {
4543     // Until the importer can support immAllZerosV in pattern leaf nodes,
4544     // select a zero move manually here.
4545     Register DstReg = I.getOperand(0).getReg();
4546     if (DstSize == 128) {
4547       auto Mov = MIB.buildInstr(AArch64::MOVIv2d_ns, {DstReg}, {}).addImm(0);
4548       I.eraseFromParent();
4549       return constrainSelectedInstRegOperands(*Mov, TII, TRI, RBI);
4550     } else if (DstSize == 64) {
4551       auto Mov =
4552           MIB.buildInstr(AArch64::MOVIv2d_ns, {&AArch64::FPR128RegClass}, {})
4553               .addImm(0);
4554       MIB.buildInstr(TargetOpcode::COPY, {DstReg}, {})
4555           .addReg(Mov.getReg(0), 0, AArch64::dsub);
4556       I.eraseFromParent();
4557       return RBI.constrainGenericRegister(DstReg, AArch64::FPR64RegClass, MRI);
4558     }
4559   }
4560   auto *CPLoad = emitLoadFromConstantPool(CV, MIB);
4561   if (!CPLoad) {
4562     LLVM_DEBUG(dbgs() << "Could not generate cp load for build_vector");
4563     return false;
4564   }
4565   MIB.buildCopy(I.getOperand(0), CPLoad->getOperand(0));
4566   RBI.constrainGenericRegister(I.getOperand(0).getReg(),
4567                                *MRI.getRegClass(CPLoad->getOperand(0).getReg()),
4568                                MRI);
4569   I.eraseFromParent();
4570   return true;
4571 }
4572 
4573 bool AArch64InstructionSelector::selectBuildVector(
4574     MachineInstr &I, MachineRegisterInfo &MRI) const {
4575   assert(I.getOpcode() == TargetOpcode::G_BUILD_VECTOR);
4576   // Until we port more of the optimized selections, for now just use a vector
4577   // insert sequence.
4578   const LLT DstTy = MRI.getType(I.getOperand(0).getReg());
4579   const LLT EltTy = MRI.getType(I.getOperand(1).getReg());
4580   unsigned EltSize = EltTy.getSizeInBits();
4581 
4582   if (tryOptConstantBuildVec(I, DstTy, MRI))
4583     return true;
4584   if (EltSize < 16 || EltSize > 64)
4585     return false; // Don't support all element types yet.
4586   const RegisterBank &RB = *RBI.getRegBank(I.getOperand(1).getReg(), MRI, TRI);
4587   MachineIRBuilder MIRBuilder(I);
4588 
4589   const TargetRegisterClass *DstRC = &AArch64::FPR128RegClass;
4590   MachineInstr *ScalarToVec =
4591       emitScalarToVector(DstTy.getElementType().getSizeInBits(), DstRC,
4592                          I.getOperand(1).getReg(), MIRBuilder);
4593   if (!ScalarToVec)
4594     return false;
4595 
4596   Register DstVec = ScalarToVec->getOperand(0).getReg();
4597   unsigned DstSize = DstTy.getSizeInBits();
4598 
4599   // Keep track of the last MI we inserted. Later on, we might be able to save
4600   // a copy using it.
4601   MachineInstr *PrevMI = nullptr;
4602   for (unsigned i = 2, e = DstSize / EltSize + 1; i < e; ++i) {
4603     // Note that if we don't do a subregister copy, we can end up making an
4604     // extra register.
4605     PrevMI = &*emitLaneInsert(None, DstVec, I.getOperand(i).getReg(), i - 1, RB,
4606                               MIRBuilder);
4607     DstVec = PrevMI->getOperand(0).getReg();
4608   }
4609 
4610   // If DstTy's size in bits is less than 128, then emit a subregister copy
4611   // from DstVec to the last register we've defined.
4612   if (DstSize < 128) {
4613     // Force this to be FPR using the destination vector.
4614     const TargetRegisterClass *RC =
4615         getMinClassForRegBank(*RBI.getRegBank(DstVec, MRI, TRI), DstSize);
4616     if (!RC)
4617       return false;
4618     if (RC != &AArch64::FPR32RegClass && RC != &AArch64::FPR64RegClass) {
4619       LLVM_DEBUG(dbgs() << "Unsupported register class!\n");
4620       return false;
4621     }
4622 
4623     unsigned SubReg = 0;
4624     if (!getSubRegForClass(RC, TRI, SubReg))
4625       return false;
4626     if (SubReg != AArch64::ssub && SubReg != AArch64::dsub) {
4627       LLVM_DEBUG(dbgs() << "Unsupported destination size! (" << DstSize
4628                         << "\n");
4629       return false;
4630     }
4631 
4632     Register Reg = MRI.createVirtualRegister(RC);
4633     Register DstReg = I.getOperand(0).getReg();
4634 
4635     MIRBuilder.buildInstr(TargetOpcode::COPY, {DstReg}, {})
4636         .addReg(DstVec, 0, SubReg);
4637     MachineOperand &RegOp = I.getOperand(1);
4638     RegOp.setReg(Reg);
4639     RBI.constrainGenericRegister(DstReg, *RC, MRI);
4640   } else {
4641     // We don't need a subregister copy. Save a copy by re-using the
4642     // destination register on the final insert.
4643     assert(PrevMI && "PrevMI was null?");
4644     PrevMI->getOperand(0).setReg(I.getOperand(0).getReg());
4645     constrainSelectedInstRegOperands(*PrevMI, TII, TRI, RBI);
4646   }
4647 
4648   I.eraseFromParent();
4649   return true;
4650 }
4651 
4652 /// Helper function to find an intrinsic ID on an a MachineInstr. Returns the
4653 /// ID if it exists, and 0 otherwise.
4654 static unsigned findIntrinsicID(MachineInstr &I) {
4655   auto IntrinOp = find_if(I.operands(), [&](const MachineOperand &Op) {
4656     return Op.isIntrinsicID();
4657   });
4658   if (IntrinOp == I.operands_end())
4659     return 0;
4660   return IntrinOp->getIntrinsicID();
4661 }
4662 
4663 bool AArch64InstructionSelector::selectIntrinsicWithSideEffects(
4664     MachineInstr &I, MachineRegisterInfo &MRI) const {
4665   // Find the intrinsic ID.
4666   unsigned IntrinID = findIntrinsicID(I);
4667   if (!IntrinID)
4668     return false;
4669   MachineIRBuilder MIRBuilder(I);
4670 
4671   // Select the instruction.
4672   switch (IntrinID) {
4673   default:
4674     return false;
4675   case Intrinsic::trap:
4676     MIRBuilder.buildInstr(AArch64::BRK, {}, {}).addImm(1);
4677     break;
4678   case Intrinsic::debugtrap:
4679     MIRBuilder.buildInstr(AArch64::BRK, {}, {}).addImm(0xF000);
4680     break;
4681   }
4682 
4683   I.eraseFromParent();
4684   return true;
4685 }
4686 
4687 bool AArch64InstructionSelector::selectIntrinsic(MachineInstr &I,
4688                                                  MachineRegisterInfo &MRI) {
4689   unsigned IntrinID = findIntrinsicID(I);
4690   if (!IntrinID)
4691     return false;
4692   MachineIRBuilder MIRBuilder(I);
4693 
4694   switch (IntrinID) {
4695   default:
4696     break;
4697   case Intrinsic::aarch64_crypto_sha1h: {
4698     Register DstReg = I.getOperand(0).getReg();
4699     Register SrcReg = I.getOperand(2).getReg();
4700 
4701     // FIXME: Should this be an assert?
4702     if (MRI.getType(DstReg).getSizeInBits() != 32 ||
4703         MRI.getType(SrcReg).getSizeInBits() != 32)
4704       return false;
4705 
4706     // The operation has to happen on FPRs. Set up some new FPR registers for
4707     // the source and destination if they are on GPRs.
4708     if (RBI.getRegBank(SrcReg, MRI, TRI)->getID() != AArch64::FPRRegBankID) {
4709       SrcReg = MRI.createVirtualRegister(&AArch64::FPR32RegClass);
4710       MIRBuilder.buildCopy({SrcReg}, {I.getOperand(2)});
4711 
4712       // Make sure the copy ends up getting constrained properly.
4713       RBI.constrainGenericRegister(I.getOperand(2).getReg(),
4714                                    AArch64::GPR32RegClass, MRI);
4715     }
4716 
4717     if (RBI.getRegBank(DstReg, MRI, TRI)->getID() != AArch64::FPRRegBankID)
4718       DstReg = MRI.createVirtualRegister(&AArch64::FPR32RegClass);
4719 
4720     // Actually insert the instruction.
4721     auto SHA1Inst = MIRBuilder.buildInstr(AArch64::SHA1Hrr, {DstReg}, {SrcReg});
4722     constrainSelectedInstRegOperands(*SHA1Inst, TII, TRI, RBI);
4723 
4724     // Did we create a new register for the destination?
4725     if (DstReg != I.getOperand(0).getReg()) {
4726       // Yep. Copy the result of the instruction back into the original
4727       // destination.
4728       MIRBuilder.buildCopy({I.getOperand(0)}, {DstReg});
4729       RBI.constrainGenericRegister(I.getOperand(0).getReg(),
4730                                    AArch64::GPR32RegClass, MRI);
4731     }
4732 
4733     I.eraseFromParent();
4734     return true;
4735   }
4736   case Intrinsic::frameaddress:
4737   case Intrinsic::returnaddress: {
4738     MachineFunction &MF = *I.getParent()->getParent();
4739     MachineFrameInfo &MFI = MF.getFrameInfo();
4740 
4741     unsigned Depth = I.getOperand(2).getImm();
4742     Register DstReg = I.getOperand(0).getReg();
4743     RBI.constrainGenericRegister(DstReg, AArch64::GPR64RegClass, MRI);
4744 
4745     if (Depth == 0 && IntrinID == Intrinsic::returnaddress) {
4746       if (!MFReturnAddr) {
4747         // Insert the copy from LR/X30 into the entry block, before it can be
4748         // clobbered by anything.
4749         MFI.setReturnAddressIsTaken(true);
4750         MFReturnAddr = getFunctionLiveInPhysReg(MF, TII, AArch64::LR,
4751                                                 AArch64::GPR64RegClass);
4752       }
4753 
4754       if (STI.hasV8_3aOps()) {
4755         MIRBuilder.buildInstr(AArch64::XPACI, {DstReg}, {MFReturnAddr});
4756       } else {
4757         MIRBuilder.buildCopy({Register(AArch64::LR)}, {MFReturnAddr});
4758         MIRBuilder.buildInstr(AArch64::XPACLRI);
4759         MIRBuilder.buildCopy({DstReg}, {Register(AArch64::LR)});
4760       }
4761 
4762       I.eraseFromParent();
4763       return true;
4764     }
4765 
4766     MFI.setFrameAddressIsTaken(true);
4767     Register FrameAddr(AArch64::FP);
4768     while (Depth--) {
4769       Register NextFrame = MRI.createVirtualRegister(&AArch64::GPR64spRegClass);
4770       auto Ldr =
4771           MIRBuilder.buildInstr(AArch64::LDRXui, {NextFrame}, {FrameAddr})
4772               .addImm(0);
4773       constrainSelectedInstRegOperands(*Ldr, TII, TRI, RBI);
4774       FrameAddr = NextFrame;
4775     }
4776 
4777     if (IntrinID == Intrinsic::frameaddress)
4778       MIRBuilder.buildCopy({DstReg}, {FrameAddr});
4779     else {
4780       MFI.setReturnAddressIsTaken(true);
4781 
4782       if (STI.hasV8_3aOps()) {
4783         Register TmpReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
4784         MIRBuilder.buildInstr(AArch64::LDRXui, {TmpReg}, {FrameAddr}).addImm(1);
4785         MIRBuilder.buildInstr(AArch64::XPACI, {DstReg}, {TmpReg});
4786       } else {
4787         MIRBuilder.buildInstr(AArch64::LDRXui, {Register(AArch64::LR)}, {FrameAddr}).addImm(1);
4788         MIRBuilder.buildInstr(AArch64::XPACLRI);
4789         MIRBuilder.buildCopy({DstReg}, {Register(AArch64::LR)});
4790       }
4791     }
4792 
4793     I.eraseFromParent();
4794     return true;
4795   }
4796   }
4797   return false;
4798 }
4799 
4800 InstructionSelector::ComplexRendererFns
4801 AArch64InstructionSelector::selectShiftA_32(const MachineOperand &Root) const {
4802   auto MaybeImmed = getImmedFromMO(Root);
4803   if (MaybeImmed == None || *MaybeImmed > 31)
4804     return None;
4805   uint64_t Enc = (32 - *MaybeImmed) & 0x1f;
4806   return {{[=](MachineInstrBuilder &MIB) { MIB.addImm(Enc); }}};
4807 }
4808 
4809 InstructionSelector::ComplexRendererFns
4810 AArch64InstructionSelector::selectShiftB_32(const MachineOperand &Root) const {
4811   auto MaybeImmed = getImmedFromMO(Root);
4812   if (MaybeImmed == None || *MaybeImmed > 31)
4813     return None;
4814   uint64_t Enc = 31 - *MaybeImmed;
4815   return {{[=](MachineInstrBuilder &MIB) { MIB.addImm(Enc); }}};
4816 }
4817 
4818 InstructionSelector::ComplexRendererFns
4819 AArch64InstructionSelector::selectShiftA_64(const MachineOperand &Root) const {
4820   auto MaybeImmed = getImmedFromMO(Root);
4821   if (MaybeImmed == None || *MaybeImmed > 63)
4822     return None;
4823   uint64_t Enc = (64 - *MaybeImmed) & 0x3f;
4824   return {{[=](MachineInstrBuilder &MIB) { MIB.addImm(Enc); }}};
4825 }
4826 
4827 InstructionSelector::ComplexRendererFns
4828 AArch64InstructionSelector::selectShiftB_64(const MachineOperand &Root) const {
4829   auto MaybeImmed = getImmedFromMO(Root);
4830   if (MaybeImmed == None || *MaybeImmed > 63)
4831     return None;
4832   uint64_t Enc = 63 - *MaybeImmed;
4833   return {{[=](MachineInstrBuilder &MIB) { MIB.addImm(Enc); }}};
4834 }
4835 
4836 /// Helper to select an immediate value that can be represented as a 12-bit
4837 /// value shifted left by either 0 or 12. If it is possible to do so, return
4838 /// the immediate and shift value. If not, return None.
4839 ///
4840 /// Used by selectArithImmed and selectNegArithImmed.
4841 InstructionSelector::ComplexRendererFns
4842 AArch64InstructionSelector::select12BitValueWithLeftShift(
4843     uint64_t Immed) const {
4844   unsigned ShiftAmt;
4845   if (Immed >> 12 == 0) {
4846     ShiftAmt = 0;
4847   } else if ((Immed & 0xfff) == 0 && Immed >> 24 == 0) {
4848     ShiftAmt = 12;
4849     Immed = Immed >> 12;
4850   } else
4851     return None;
4852 
4853   unsigned ShVal = AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftAmt);
4854   return {{
4855       [=](MachineInstrBuilder &MIB) { MIB.addImm(Immed); },
4856       [=](MachineInstrBuilder &MIB) { MIB.addImm(ShVal); },
4857   }};
4858 }
4859 
4860 /// SelectArithImmed - Select an immediate value that can be represented as
4861 /// a 12-bit value shifted left by either 0 or 12.  If so, return true with
4862 /// Val set to the 12-bit value and Shift set to the shifter operand.
4863 InstructionSelector::ComplexRendererFns
4864 AArch64InstructionSelector::selectArithImmed(MachineOperand &Root) const {
4865   // This function is called from the addsub_shifted_imm ComplexPattern,
4866   // which lists [imm] as the list of opcode it's interested in, however
4867   // we still need to check whether the operand is actually an immediate
4868   // here because the ComplexPattern opcode list is only used in
4869   // root-level opcode matching.
4870   auto MaybeImmed = getImmedFromMO(Root);
4871   if (MaybeImmed == None)
4872     return None;
4873   return select12BitValueWithLeftShift(*MaybeImmed);
4874 }
4875 
4876 /// SelectNegArithImmed - As above, but negates the value before trying to
4877 /// select it.
4878 InstructionSelector::ComplexRendererFns
4879 AArch64InstructionSelector::selectNegArithImmed(MachineOperand &Root) const {
4880   // We need a register here, because we need to know if we have a 64 or 32
4881   // bit immediate.
4882   if (!Root.isReg())
4883     return None;
4884   auto MaybeImmed = getImmedFromMO(Root);
4885   if (MaybeImmed == None)
4886     return None;
4887   uint64_t Immed = *MaybeImmed;
4888 
4889   // This negation is almost always valid, but "cmp wN, #0" and "cmn wN, #0"
4890   // have the opposite effect on the C flag, so this pattern mustn't match under
4891   // those circumstances.
4892   if (Immed == 0)
4893     return None;
4894 
4895   // Check if we're dealing with a 32-bit type on the root or a 64-bit type on
4896   // the root.
4897   MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
4898   if (MRI.getType(Root.getReg()).getSizeInBits() == 32)
4899     Immed = ~((uint32_t)Immed) + 1;
4900   else
4901     Immed = ~Immed + 1ULL;
4902 
4903   if (Immed & 0xFFFFFFFFFF000000ULL)
4904     return None;
4905 
4906   Immed &= 0xFFFFFFULL;
4907   return select12BitValueWithLeftShift(Immed);
4908 }
4909 
4910 /// Return true if it is worth folding MI into an extended register. That is,
4911 /// if it's safe to pull it into the addressing mode of a load or store as a
4912 /// shift.
4913 bool AArch64InstructionSelector::isWorthFoldingIntoExtendedReg(
4914     MachineInstr &MI, const MachineRegisterInfo &MRI) const {
4915   // Always fold if there is one use, or if we're optimizing for size.
4916   Register DefReg = MI.getOperand(0).getReg();
4917   if (MRI.hasOneNonDBGUse(DefReg) ||
4918       MI.getParent()->getParent()->getFunction().hasMinSize())
4919     return true;
4920 
4921   // It's better to avoid folding and recomputing shifts when we don't have a
4922   // fastpath.
4923   if (!STI.hasLSLFast())
4924     return false;
4925 
4926   // We have a fastpath, so folding a shift in and potentially computing it
4927   // many times may be beneficial. Check if this is only used in memory ops.
4928   // If it is, then we should fold.
4929   return all_of(MRI.use_nodbg_instructions(DefReg),
4930                 [](MachineInstr &Use) { return Use.mayLoadOrStore(); });
4931 }
4932 
4933 static bool isSignExtendShiftType(AArch64_AM::ShiftExtendType Type) {
4934   switch (Type) {
4935   case AArch64_AM::SXTB:
4936   case AArch64_AM::SXTH:
4937   case AArch64_AM::SXTW:
4938     return true;
4939   default:
4940     return false;
4941   }
4942 }
4943 
4944 InstructionSelector::ComplexRendererFns
4945 AArch64InstructionSelector::selectExtendedSHL(
4946     MachineOperand &Root, MachineOperand &Base, MachineOperand &Offset,
4947     unsigned SizeInBytes, bool WantsExt) const {
4948   assert(Base.isReg() && "Expected base to be a register operand");
4949   assert(Offset.isReg() && "Expected offset to be a register operand");
4950 
4951   MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
4952   MachineInstr *OffsetInst = MRI.getVRegDef(Offset.getReg());
4953   if (!OffsetInst)
4954     return None;
4955 
4956   unsigned OffsetOpc = OffsetInst->getOpcode();
4957   if (OffsetOpc != TargetOpcode::G_SHL && OffsetOpc != TargetOpcode::G_MUL)
4958     return None;
4959 
4960   // Make sure that the memory op is a valid size.
4961   int64_t LegalShiftVal = Log2_32(SizeInBytes);
4962   if (LegalShiftVal == 0)
4963     return None;
4964   if (!isWorthFoldingIntoExtendedReg(*OffsetInst, MRI))
4965     return None;
4966 
4967   // Now, try to find the specific G_CONSTANT. Start by assuming that the
4968   // register we will offset is the LHS, and the register containing the
4969   // constant is the RHS.
4970   Register OffsetReg = OffsetInst->getOperand(1).getReg();
4971   Register ConstantReg = OffsetInst->getOperand(2).getReg();
4972   auto ValAndVReg = getConstantVRegValWithLookThrough(ConstantReg, MRI);
4973   if (!ValAndVReg) {
4974     // We didn't get a constant on the RHS. If the opcode is a shift, then
4975     // we're done.
4976     if (OffsetOpc == TargetOpcode::G_SHL)
4977       return None;
4978 
4979     // If we have a G_MUL, we can use either register. Try looking at the RHS.
4980     std::swap(OffsetReg, ConstantReg);
4981     ValAndVReg = getConstantVRegValWithLookThrough(ConstantReg, MRI);
4982     if (!ValAndVReg)
4983       return None;
4984   }
4985 
4986   // The value must fit into 3 bits, and must be positive. Make sure that is
4987   // true.
4988   int64_t ImmVal = ValAndVReg->Value;
4989 
4990   // Since we're going to pull this into a shift, the constant value must be
4991   // a power of 2. If we got a multiply, then we need to check this.
4992   if (OffsetOpc == TargetOpcode::G_MUL) {
4993     if (!isPowerOf2_32(ImmVal))
4994       return None;
4995 
4996     // Got a power of 2. So, the amount we'll shift is the log base-2 of that.
4997     ImmVal = Log2_32(ImmVal);
4998   }
4999 
5000   if ((ImmVal & 0x7) != ImmVal)
5001     return None;
5002 
5003   // We are only allowed to shift by LegalShiftVal. This shift value is built
5004   // into the instruction, so we can't just use whatever we want.
5005   if (ImmVal != LegalShiftVal)
5006     return None;
5007 
5008   unsigned SignExtend = 0;
5009   if (WantsExt) {
5010     // Check if the offset is defined by an extend.
5011     MachineInstr *ExtInst = getDefIgnoringCopies(OffsetReg, MRI);
5012     auto Ext = getExtendTypeForInst(*ExtInst, MRI, true);
5013     if (Ext == AArch64_AM::InvalidShiftExtend)
5014       return None;
5015 
5016     SignExtend = isSignExtendShiftType(Ext) ? 1 : 0;
5017     // We only support SXTW for signed extension here.
5018     if (SignExtend && Ext != AArch64_AM::SXTW)
5019       return None;
5020 
5021     // Need a 32-bit wide register here.
5022     MachineIRBuilder MIB(*MRI.getVRegDef(Root.getReg()));
5023     OffsetReg = ExtInst->getOperand(1).getReg();
5024     OffsetReg = narrowExtendRegIfNeeded(OffsetReg, MIB);
5025   }
5026 
5027   // We can use the LHS of the GEP as the base, and the LHS of the shift as an
5028   // offset. Signify that we are shifting by setting the shift flag to 1.
5029   return {{[=](MachineInstrBuilder &MIB) { MIB.addUse(Base.getReg()); },
5030            [=](MachineInstrBuilder &MIB) { MIB.addUse(OffsetReg); },
5031            [=](MachineInstrBuilder &MIB) {
5032              // Need to add both immediates here to make sure that they are both
5033              // added to the instruction.
5034              MIB.addImm(SignExtend);
5035              MIB.addImm(1);
5036            }}};
5037 }
5038 
5039 /// This is used for computing addresses like this:
5040 ///
5041 /// ldr x1, [x2, x3, lsl #3]
5042 ///
5043 /// Where x2 is the base register, and x3 is an offset register. The shift-left
5044 /// is a constant value specific to this load instruction. That is, we'll never
5045 /// see anything other than a 3 here (which corresponds to the size of the
5046 /// element being loaded.)
5047 InstructionSelector::ComplexRendererFns
5048 AArch64InstructionSelector::selectAddrModeShiftedExtendXReg(
5049     MachineOperand &Root, unsigned SizeInBytes) const {
5050   if (!Root.isReg())
5051     return None;
5052   MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
5053 
5054   // We want to find something like this:
5055   //
5056   // val = G_CONSTANT LegalShiftVal
5057   // shift = G_SHL off_reg val
5058   // ptr = G_PTR_ADD base_reg shift
5059   // x = G_LOAD ptr
5060   //
5061   // And fold it into this addressing mode:
5062   //
5063   // ldr x, [base_reg, off_reg, lsl #LegalShiftVal]
5064 
5065   // Check if we can find the G_PTR_ADD.
5066   MachineInstr *PtrAdd =
5067       getOpcodeDef(TargetOpcode::G_PTR_ADD, Root.getReg(), MRI);
5068   if (!PtrAdd || !isWorthFoldingIntoExtendedReg(*PtrAdd, MRI))
5069     return None;
5070 
5071   // Now, try to match an opcode which will match our specific offset.
5072   // We want a G_SHL or a G_MUL.
5073   MachineInstr *OffsetInst =
5074       getDefIgnoringCopies(PtrAdd->getOperand(2).getReg(), MRI);
5075   return selectExtendedSHL(Root, PtrAdd->getOperand(1),
5076                            OffsetInst->getOperand(0), SizeInBytes,
5077                            /*WantsExt=*/false);
5078 }
5079 
5080 /// This is used for computing addresses like this:
5081 ///
5082 /// ldr x1, [x2, x3]
5083 ///
5084 /// Where x2 is the base register, and x3 is an offset register.
5085 ///
5086 /// When possible (or profitable) to fold a G_PTR_ADD into the address calculation,
5087 /// this will do so. Otherwise, it will return None.
5088 InstructionSelector::ComplexRendererFns
5089 AArch64InstructionSelector::selectAddrModeRegisterOffset(
5090     MachineOperand &Root) const {
5091   MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
5092 
5093   // We need a GEP.
5094   MachineInstr *Gep = MRI.getVRegDef(Root.getReg());
5095   if (!Gep || Gep->getOpcode() != TargetOpcode::G_PTR_ADD)
5096     return None;
5097 
5098   // If this is used more than once, let's not bother folding.
5099   // TODO: Check if they are memory ops. If they are, then we can still fold
5100   // without having to recompute anything.
5101   if (!MRI.hasOneNonDBGUse(Gep->getOperand(0).getReg()))
5102     return None;
5103 
5104   // Base is the GEP's LHS, offset is its RHS.
5105   return {{[=](MachineInstrBuilder &MIB) {
5106              MIB.addUse(Gep->getOperand(1).getReg());
5107            },
5108            [=](MachineInstrBuilder &MIB) {
5109              MIB.addUse(Gep->getOperand(2).getReg());
5110            },
5111            [=](MachineInstrBuilder &MIB) {
5112              // Need to add both immediates here to make sure that they are both
5113              // added to the instruction.
5114              MIB.addImm(0);
5115              MIB.addImm(0);
5116            }}};
5117 }
5118 
5119 /// This is intended to be equivalent to selectAddrModeXRO in
5120 /// AArch64ISelDAGtoDAG. It's used for selecting X register offset loads.
5121 InstructionSelector::ComplexRendererFns
5122 AArch64InstructionSelector::selectAddrModeXRO(MachineOperand &Root,
5123                                               unsigned SizeInBytes) const {
5124   MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
5125   if (!Root.isReg())
5126     return None;
5127   MachineInstr *PtrAdd =
5128       getOpcodeDef(TargetOpcode::G_PTR_ADD, Root.getReg(), MRI);
5129   if (!PtrAdd)
5130     return None;
5131 
5132   // Check for an immediates which cannot be encoded in the [base + imm]
5133   // addressing mode, and can't be encoded in an add/sub. If this happens, we'll
5134   // end up with code like:
5135   //
5136   // mov x0, wide
5137   // add x1 base, x0
5138   // ldr x2, [x1, x0]
5139   //
5140   // In this situation, we can use the [base, xreg] addressing mode to save an
5141   // add/sub:
5142   //
5143   // mov x0, wide
5144   // ldr x2, [base, x0]
5145   auto ValAndVReg =
5146       getConstantVRegValWithLookThrough(PtrAdd->getOperand(2).getReg(), MRI);
5147   if (ValAndVReg) {
5148     unsigned Scale = Log2_32(SizeInBytes);
5149     int64_t ImmOff = ValAndVReg->Value;
5150 
5151     // Skip immediates that can be selected in the load/store addresing
5152     // mode.
5153     if (ImmOff % SizeInBytes == 0 && ImmOff >= 0 &&
5154         ImmOff < (0x1000 << Scale))
5155       return None;
5156 
5157     // Helper lambda to decide whether or not it is preferable to emit an add.
5158     auto isPreferredADD = [](int64_t ImmOff) {
5159       // Constants in [0x0, 0xfff] can be encoded in an add.
5160       if ((ImmOff & 0xfffffffffffff000LL) == 0x0LL)
5161         return true;
5162 
5163       // Can it be encoded in an add lsl #12?
5164       if ((ImmOff & 0xffffffffff000fffLL) != 0x0LL)
5165         return false;
5166 
5167       // It can be encoded in an add lsl #12, but we may not want to. If it is
5168       // possible to select this as a single movz, then prefer that. A single
5169       // movz is faster than an add with a shift.
5170       return (ImmOff & 0xffffffffff00ffffLL) != 0x0LL &&
5171              (ImmOff & 0xffffffffffff0fffLL) != 0x0LL;
5172     };
5173 
5174     // If the immediate can be encoded in a single add/sub, then bail out.
5175     if (isPreferredADD(ImmOff) || isPreferredADD(-ImmOff))
5176       return None;
5177   }
5178 
5179   // Try to fold shifts into the addressing mode.
5180   auto AddrModeFns = selectAddrModeShiftedExtendXReg(Root, SizeInBytes);
5181   if (AddrModeFns)
5182     return AddrModeFns;
5183 
5184   // If that doesn't work, see if it's possible to fold in registers from
5185   // a GEP.
5186   return selectAddrModeRegisterOffset(Root);
5187 }
5188 
5189 /// This is used for computing addresses like this:
5190 ///
5191 /// ldr x0, [xBase, wOffset, sxtw #LegalShiftVal]
5192 ///
5193 /// Where we have a 64-bit base register, a 32-bit offset register, and an
5194 /// extend (which may or may not be signed).
5195 InstructionSelector::ComplexRendererFns
5196 AArch64InstructionSelector::selectAddrModeWRO(MachineOperand &Root,
5197                                               unsigned SizeInBytes) const {
5198   MachineRegisterInfo &MRI = Root.getParent()->getMF()->getRegInfo();
5199 
5200   MachineInstr *PtrAdd =
5201       getOpcodeDef(TargetOpcode::G_PTR_ADD, Root.getReg(), MRI);
5202   if (!PtrAdd || !isWorthFoldingIntoExtendedReg(*PtrAdd, MRI))
5203     return None;
5204 
5205   MachineOperand &LHS = PtrAdd->getOperand(1);
5206   MachineOperand &RHS = PtrAdd->getOperand(2);
5207   MachineInstr *OffsetInst = getDefIgnoringCopies(RHS.getReg(), MRI);
5208 
5209   // The first case is the same as selectAddrModeXRO, except we need an extend.
5210   // In this case, we try to find a shift and extend, and fold them into the
5211   // addressing mode.
5212   //
5213   // E.g.
5214   //
5215   // off_reg = G_Z/S/ANYEXT ext_reg
5216   // val = G_CONSTANT LegalShiftVal
5217   // shift = G_SHL off_reg val
5218   // ptr = G_PTR_ADD base_reg shift
5219   // x = G_LOAD ptr
5220   //
5221   // In this case we can get a load like this:
5222   //
5223   // ldr x0, [base_reg, ext_reg, sxtw #LegalShiftVal]
5224   auto ExtendedShl = selectExtendedSHL(Root, LHS, OffsetInst->getOperand(0),
5225                                        SizeInBytes, /*WantsExt=*/true);
5226   if (ExtendedShl)
5227     return ExtendedShl;
5228 
5229   // There was no shift. We can try and fold a G_Z/S/ANYEXT in alone though.
5230   //
5231   // e.g.
5232   // ldr something, [base_reg, ext_reg, sxtw]
5233   if (!isWorthFoldingIntoExtendedReg(*OffsetInst, MRI))
5234     return None;
5235 
5236   // Check if this is an extend. We'll get an extend type if it is.
5237   AArch64_AM::ShiftExtendType Ext =
5238       getExtendTypeForInst(*OffsetInst, MRI, /*IsLoadStore=*/true);
5239   if (Ext == AArch64_AM::InvalidShiftExtend)
5240     return None;
5241 
5242   // Need a 32-bit wide register.
5243   MachineIRBuilder MIB(*PtrAdd);
5244   Register ExtReg =
5245       narrowExtendRegIfNeeded(OffsetInst->getOperand(1).getReg(), MIB);
5246   unsigned SignExtend = Ext == AArch64_AM::SXTW;
5247 
5248   // Base is LHS, offset is ExtReg.
5249   return {{[=](MachineInstrBuilder &MIB) { MIB.addUse(LHS.getReg()); },
5250            [=](MachineInstrBuilder &MIB) { MIB.addUse(ExtReg); },
5251            [=](MachineInstrBuilder &MIB) {
5252              MIB.addImm(SignExtend);
5253              MIB.addImm(0);
5254            }}};
5255 }
5256 
5257 /// Select a "register plus unscaled signed 9-bit immediate" address.  This
5258 /// should only match when there is an offset that is not valid for a scaled
5259 /// immediate addressing mode.  The "Size" argument is the size in bytes of the
5260 /// memory reference, which is needed here to know what is valid for a scaled
5261 /// immediate.
5262 InstructionSelector::ComplexRendererFns
5263 AArch64InstructionSelector::selectAddrModeUnscaled(MachineOperand &Root,
5264                                                    unsigned Size) const {
5265   MachineRegisterInfo &MRI =
5266       Root.getParent()->getParent()->getParent()->getRegInfo();
5267 
5268   if (!Root.isReg())
5269     return None;
5270 
5271   if (!isBaseWithConstantOffset(Root, MRI))
5272     return None;
5273 
5274   MachineInstr *RootDef = MRI.getVRegDef(Root.getReg());
5275   if (!RootDef)
5276     return None;
5277 
5278   MachineOperand &OffImm = RootDef->getOperand(2);
5279   if (!OffImm.isReg())
5280     return None;
5281   MachineInstr *RHS = MRI.getVRegDef(OffImm.getReg());
5282   if (!RHS || RHS->getOpcode() != TargetOpcode::G_CONSTANT)
5283     return None;
5284   int64_t RHSC;
5285   MachineOperand &RHSOp1 = RHS->getOperand(1);
5286   if (!RHSOp1.isCImm() || RHSOp1.getCImm()->getBitWidth() > 64)
5287     return None;
5288   RHSC = RHSOp1.getCImm()->getSExtValue();
5289 
5290   // If the offset is valid as a scaled immediate, don't match here.
5291   if ((RHSC & (Size - 1)) == 0 && RHSC >= 0 && RHSC < (0x1000 << Log2_32(Size)))
5292     return None;
5293   if (RHSC >= -256 && RHSC < 256) {
5294     MachineOperand &Base = RootDef->getOperand(1);
5295     return {{
5296         [=](MachineInstrBuilder &MIB) { MIB.add(Base); },
5297         [=](MachineInstrBuilder &MIB) { MIB.addImm(RHSC); },
5298     }};
5299   }
5300   return None;
5301 }
5302 
5303 InstructionSelector::ComplexRendererFns
5304 AArch64InstructionSelector::tryFoldAddLowIntoImm(MachineInstr &RootDef,
5305                                                  unsigned Size,
5306                                                  MachineRegisterInfo &MRI) const {
5307   if (RootDef.getOpcode() != AArch64::G_ADD_LOW)
5308     return None;
5309   MachineInstr &Adrp = *MRI.getVRegDef(RootDef.getOperand(1).getReg());
5310   if (Adrp.getOpcode() != AArch64::ADRP)
5311     return None;
5312 
5313   // TODO: add heuristics like isWorthFoldingADDlow() from SelectionDAG.
5314   // TODO: Need to check GV's offset % size if doing offset folding into globals.
5315   assert(Adrp.getOperand(1).getOffset() == 0 && "Unexpected offset in global");
5316   auto GV = Adrp.getOperand(1).getGlobal();
5317   if (GV->isThreadLocal())
5318     return None;
5319 
5320   auto &MF = *RootDef.getParent()->getParent();
5321   if (GV->getPointerAlignment(MF.getDataLayout()) < Size)
5322     return None;
5323 
5324   unsigned OpFlags = STI.ClassifyGlobalReference(GV, MF.getTarget());
5325   MachineIRBuilder MIRBuilder(RootDef);
5326   Register AdrpReg = Adrp.getOperand(0).getReg();
5327   return {{[=](MachineInstrBuilder &MIB) { MIB.addUse(AdrpReg); },
5328            [=](MachineInstrBuilder &MIB) {
5329              MIB.addGlobalAddress(GV, /* Offset */ 0,
5330                                   OpFlags | AArch64II::MO_PAGEOFF |
5331                                       AArch64II::MO_NC);
5332            }}};
5333 }
5334 
5335 /// Select a "register plus scaled unsigned 12-bit immediate" address.  The
5336 /// "Size" argument is the size in bytes of the memory reference, which
5337 /// determines the scale.
5338 InstructionSelector::ComplexRendererFns
5339 AArch64InstructionSelector::selectAddrModeIndexed(MachineOperand &Root,
5340                                                   unsigned Size) const {
5341   MachineFunction &MF = *Root.getParent()->getParent()->getParent();
5342   MachineRegisterInfo &MRI = MF.getRegInfo();
5343 
5344   if (!Root.isReg())
5345     return None;
5346 
5347   MachineInstr *RootDef = MRI.getVRegDef(Root.getReg());
5348   if (!RootDef)
5349     return None;
5350 
5351   if (RootDef->getOpcode() == TargetOpcode::G_FRAME_INDEX) {
5352     return {{
5353         [=](MachineInstrBuilder &MIB) { MIB.add(RootDef->getOperand(1)); },
5354         [=](MachineInstrBuilder &MIB) { MIB.addImm(0); },
5355     }};
5356   }
5357 
5358   CodeModel::Model CM = MF.getTarget().getCodeModel();
5359   // Check if we can fold in the ADD of small code model ADRP + ADD address.
5360   if (CM == CodeModel::Small) {
5361     auto OpFns = tryFoldAddLowIntoImm(*RootDef, Size, MRI);
5362     if (OpFns)
5363       return OpFns;
5364   }
5365 
5366   if (isBaseWithConstantOffset(Root, MRI)) {
5367     MachineOperand &LHS = RootDef->getOperand(1);
5368     MachineOperand &RHS = RootDef->getOperand(2);
5369     MachineInstr *LHSDef = MRI.getVRegDef(LHS.getReg());
5370     MachineInstr *RHSDef = MRI.getVRegDef(RHS.getReg());
5371     if (LHSDef && RHSDef) {
5372       int64_t RHSC = (int64_t)RHSDef->getOperand(1).getCImm()->getZExtValue();
5373       unsigned Scale = Log2_32(Size);
5374       if ((RHSC & (Size - 1)) == 0 && RHSC >= 0 && RHSC < (0x1000 << Scale)) {
5375         if (LHSDef->getOpcode() == TargetOpcode::G_FRAME_INDEX)
5376           return {{
5377               [=](MachineInstrBuilder &MIB) { MIB.add(LHSDef->getOperand(1)); },
5378               [=](MachineInstrBuilder &MIB) { MIB.addImm(RHSC >> Scale); },
5379           }};
5380 
5381         return {{
5382             [=](MachineInstrBuilder &MIB) { MIB.add(LHS); },
5383             [=](MachineInstrBuilder &MIB) { MIB.addImm(RHSC >> Scale); },
5384         }};
5385       }
5386     }
5387   }
5388 
5389   // Before falling back to our general case, check if the unscaled
5390   // instructions can handle this. If so, that's preferable.
5391   if (selectAddrModeUnscaled(Root, Size).hasValue())
5392     return None;
5393 
5394   return {{
5395       [=](MachineInstrBuilder &MIB) { MIB.add(Root); },
5396       [=](MachineInstrBuilder &MIB) { MIB.addImm(0); },
5397   }};
5398 }
5399 
5400 /// Given a shift instruction, return the correct shift type for that
5401 /// instruction.
5402 static AArch64_AM::ShiftExtendType getShiftTypeForInst(MachineInstr &MI) {
5403   // TODO: Handle AArch64_AM::ROR
5404   switch (MI.getOpcode()) {
5405   default:
5406     return AArch64_AM::InvalidShiftExtend;
5407   case TargetOpcode::G_SHL:
5408     return AArch64_AM::LSL;
5409   case TargetOpcode::G_LSHR:
5410     return AArch64_AM::LSR;
5411   case TargetOpcode::G_ASHR:
5412     return AArch64_AM::ASR;
5413   }
5414 }
5415 
5416 /// Select a "shifted register" operand. If the value is not shifted, set the
5417 /// shift operand to a default value of "lsl 0".
5418 ///
5419 /// TODO: Allow shifted register to be rotated in logical instructions.
5420 InstructionSelector::ComplexRendererFns
5421 AArch64InstructionSelector::selectShiftedRegister(MachineOperand &Root) const {
5422   if (!Root.isReg())
5423     return None;
5424   MachineRegisterInfo &MRI =
5425       Root.getParent()->getParent()->getParent()->getRegInfo();
5426 
5427   // Check if the operand is defined by an instruction which corresponds to
5428   // a ShiftExtendType. E.g. a G_SHL, G_LSHR, etc.
5429   //
5430   // TODO: Handle AArch64_AM::ROR for logical instructions.
5431   MachineInstr *ShiftInst = MRI.getVRegDef(Root.getReg());
5432   if (!ShiftInst)
5433     return None;
5434   AArch64_AM::ShiftExtendType ShType = getShiftTypeForInst(*ShiftInst);
5435   if (ShType == AArch64_AM::InvalidShiftExtend)
5436     return None;
5437   if (!isWorthFoldingIntoExtendedReg(*ShiftInst, MRI))
5438     return None;
5439 
5440   // Need an immediate on the RHS.
5441   MachineOperand &ShiftRHS = ShiftInst->getOperand(2);
5442   auto Immed = getImmedFromMO(ShiftRHS);
5443   if (!Immed)
5444     return None;
5445 
5446   // We have something that we can fold. Fold in the shift's LHS and RHS into
5447   // the instruction.
5448   MachineOperand &ShiftLHS = ShiftInst->getOperand(1);
5449   Register ShiftReg = ShiftLHS.getReg();
5450 
5451   unsigned NumBits = MRI.getType(ShiftReg).getSizeInBits();
5452   unsigned Val = *Immed & (NumBits - 1);
5453   unsigned ShiftVal = AArch64_AM::getShifterImm(ShType, Val);
5454 
5455   return {{[=](MachineInstrBuilder &MIB) { MIB.addUse(ShiftReg); },
5456            [=](MachineInstrBuilder &MIB) { MIB.addImm(ShiftVal); }}};
5457 }
5458 
5459 AArch64_AM::ShiftExtendType AArch64InstructionSelector::getExtendTypeForInst(
5460     MachineInstr &MI, MachineRegisterInfo &MRI, bool IsLoadStore) const {
5461   unsigned Opc = MI.getOpcode();
5462 
5463   // Handle explicit extend instructions first.
5464   if (Opc == TargetOpcode::G_SEXT || Opc == TargetOpcode::G_SEXT_INREG) {
5465     unsigned Size;
5466     if (Opc == TargetOpcode::G_SEXT)
5467       Size = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
5468     else
5469       Size = MI.getOperand(2).getImm();
5470     assert(Size != 64 && "Extend from 64 bits?");
5471     switch (Size) {
5472     case 8:
5473       return AArch64_AM::SXTB;
5474     case 16:
5475       return AArch64_AM::SXTH;
5476     case 32:
5477       return AArch64_AM::SXTW;
5478     default:
5479       return AArch64_AM::InvalidShiftExtend;
5480     }
5481   }
5482 
5483   if (Opc == TargetOpcode::G_ZEXT || Opc == TargetOpcode::G_ANYEXT) {
5484     unsigned Size = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
5485     assert(Size != 64 && "Extend from 64 bits?");
5486     switch (Size) {
5487     case 8:
5488       return AArch64_AM::UXTB;
5489     case 16:
5490       return AArch64_AM::UXTH;
5491     case 32:
5492       return AArch64_AM::UXTW;
5493     default:
5494       return AArch64_AM::InvalidShiftExtend;
5495     }
5496   }
5497 
5498   // Don't have an explicit extend. Try to handle a G_AND with a constant mask
5499   // on the RHS.
5500   if (Opc != TargetOpcode::G_AND)
5501     return AArch64_AM::InvalidShiftExtend;
5502 
5503   Optional<uint64_t> MaybeAndMask = getImmedFromMO(MI.getOperand(2));
5504   if (!MaybeAndMask)
5505     return AArch64_AM::InvalidShiftExtend;
5506   uint64_t AndMask = *MaybeAndMask;
5507   switch (AndMask) {
5508   default:
5509     return AArch64_AM::InvalidShiftExtend;
5510   case 0xFF:
5511     return !IsLoadStore ? AArch64_AM::UXTB : AArch64_AM::InvalidShiftExtend;
5512   case 0xFFFF:
5513     return !IsLoadStore ? AArch64_AM::UXTH : AArch64_AM::InvalidShiftExtend;
5514   case 0xFFFFFFFF:
5515     return AArch64_AM::UXTW;
5516   }
5517 }
5518 
5519 Register AArch64InstructionSelector::narrowExtendRegIfNeeded(
5520     Register ExtReg, MachineIRBuilder &MIB) const {
5521   MachineRegisterInfo &MRI = *MIB.getMRI();
5522   if (MRI.getType(ExtReg).getSizeInBits() == 32)
5523     return ExtReg;
5524 
5525   // Insert a copy to move ExtReg to GPR32.
5526   Register NarrowReg = MRI.createVirtualRegister(&AArch64::GPR32RegClass);
5527   auto Copy = MIB.buildCopy({NarrowReg}, {ExtReg});
5528 
5529   // Select the copy into a subregister copy.
5530   selectCopy(*Copy, TII, MRI, TRI, RBI);
5531   return Copy.getReg(0);
5532 }
5533 
5534 Register AArch64InstructionSelector::widenGPRBankRegIfNeeded(
5535     Register Reg, unsigned WideSize, MachineIRBuilder &MIB) const {
5536   assert(WideSize >= 8 && "WideSize is smaller than all possible registers?");
5537   MachineRegisterInfo &MRI = *MIB.getMRI();
5538   unsigned NarrowSize = MRI.getType(Reg).getSizeInBits();
5539   assert(WideSize >= NarrowSize &&
5540          "WideSize cannot be smaller than NarrowSize!");
5541 
5542   // If the sizes match, just return the register.
5543   //
5544   // If NarrowSize is an s1, then we can select it to any size, so we'll treat
5545   // it as a don't care.
5546   if (NarrowSize == WideSize || NarrowSize == 1)
5547     return Reg;
5548 
5549   // Now check the register classes.
5550   const RegisterBank *RB = RBI.getRegBank(Reg, MRI, TRI);
5551   const TargetRegisterClass *OrigRC = getMinClassForRegBank(*RB, NarrowSize);
5552   const TargetRegisterClass *WideRC = getMinClassForRegBank(*RB, WideSize);
5553   assert(OrigRC && "Could not determine narrow RC?");
5554   assert(WideRC && "Could not determine wide RC?");
5555 
5556   // If the sizes differ, but the register classes are the same, there is no
5557   // need to insert a SUBREG_TO_REG.
5558   //
5559   // For example, an s8 that's supposed to be a GPR will be selected to either
5560   // a GPR32 or a GPR64 register. Note that this assumes that the s8 will
5561   // always end up on a GPR32.
5562   if (OrigRC == WideRC)
5563     return Reg;
5564 
5565   // We have two different register classes. Insert a SUBREG_TO_REG.
5566   unsigned SubReg = 0;
5567   getSubRegForClass(OrigRC, TRI, SubReg);
5568   assert(SubReg && "Couldn't determine subregister?");
5569 
5570   // Build the SUBREG_TO_REG and return the new, widened register.
5571   auto SubRegToReg =
5572       MIB.buildInstr(AArch64::SUBREG_TO_REG, {WideRC}, {})
5573           .addImm(0)
5574           .addUse(Reg)
5575           .addImm(SubReg);
5576   constrainSelectedInstRegOperands(*SubRegToReg, TII, TRI, RBI);
5577   return SubRegToReg.getReg(0);
5578 }
5579 
5580 /// Select an "extended register" operand. This operand folds in an extend
5581 /// followed by an optional left shift.
5582 InstructionSelector::ComplexRendererFns
5583 AArch64InstructionSelector::selectArithExtendedRegister(
5584     MachineOperand &Root) const {
5585   if (!Root.isReg())
5586     return None;
5587   MachineRegisterInfo &MRI =
5588       Root.getParent()->getParent()->getParent()->getRegInfo();
5589 
5590   uint64_t ShiftVal = 0;
5591   Register ExtReg;
5592   AArch64_AM::ShiftExtendType Ext;
5593   MachineInstr *RootDef = getDefIgnoringCopies(Root.getReg(), MRI);
5594   if (!RootDef)
5595     return None;
5596 
5597   if (!isWorthFoldingIntoExtendedReg(*RootDef, MRI))
5598     return None;
5599 
5600   // Check if we can fold a shift and an extend.
5601   if (RootDef->getOpcode() == TargetOpcode::G_SHL) {
5602     // Look for a constant on the RHS of the shift.
5603     MachineOperand &RHS = RootDef->getOperand(2);
5604     Optional<uint64_t> MaybeShiftVal = getImmedFromMO(RHS);
5605     if (!MaybeShiftVal)
5606       return None;
5607     ShiftVal = *MaybeShiftVal;
5608     if (ShiftVal > 4)
5609       return None;
5610     // Look for a valid extend instruction on the LHS of the shift.
5611     MachineOperand &LHS = RootDef->getOperand(1);
5612     MachineInstr *ExtDef = getDefIgnoringCopies(LHS.getReg(), MRI);
5613     if (!ExtDef)
5614       return None;
5615     Ext = getExtendTypeForInst(*ExtDef, MRI);
5616     if (Ext == AArch64_AM::InvalidShiftExtend)
5617       return None;
5618     ExtReg = ExtDef->getOperand(1).getReg();
5619   } else {
5620     // Didn't get a shift. Try just folding an extend.
5621     Ext = getExtendTypeForInst(*RootDef, MRI);
5622     if (Ext == AArch64_AM::InvalidShiftExtend)
5623       return None;
5624     ExtReg = RootDef->getOperand(1).getReg();
5625 
5626     // If we have a 32 bit instruction which zeroes out the high half of a
5627     // register, we get an implicit zero extend for free. Check if we have one.
5628     // FIXME: We actually emit the extend right now even though we don't have
5629     // to.
5630     if (Ext == AArch64_AM::UXTW && MRI.getType(ExtReg).getSizeInBits() == 32) {
5631       MachineInstr *ExtInst = MRI.getVRegDef(ExtReg);
5632       if (ExtInst && isDef32(*ExtInst))
5633         return None;
5634     }
5635   }
5636 
5637   // We require a GPR32 here. Narrow the ExtReg if needed using a subregister
5638   // copy.
5639   MachineIRBuilder MIB(*RootDef);
5640   ExtReg = narrowExtendRegIfNeeded(ExtReg, MIB);
5641 
5642   return {{[=](MachineInstrBuilder &MIB) { MIB.addUse(ExtReg); },
5643            [=](MachineInstrBuilder &MIB) {
5644              MIB.addImm(getArithExtendImm(Ext, ShiftVal));
5645            }}};
5646 }
5647 
5648 void AArch64InstructionSelector::renderTruncImm(MachineInstrBuilder &MIB,
5649                                                 const MachineInstr &MI,
5650                                                 int OpIdx) const {
5651   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
5652   assert(MI.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
5653          "Expected G_CONSTANT");
5654   Optional<int64_t> CstVal = getConstantVRegVal(MI.getOperand(0).getReg(), MRI);
5655   assert(CstVal && "Expected constant value");
5656   MIB.addImm(CstVal.getValue());
5657 }
5658 
5659 void AArch64InstructionSelector::renderLogicalImm32(
5660   MachineInstrBuilder &MIB, const MachineInstr &I, int OpIdx) const {
5661   assert(I.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
5662          "Expected G_CONSTANT");
5663   uint64_t CstVal = I.getOperand(1).getCImm()->getZExtValue();
5664   uint64_t Enc = AArch64_AM::encodeLogicalImmediate(CstVal, 32);
5665   MIB.addImm(Enc);
5666 }
5667 
5668 void AArch64InstructionSelector::renderLogicalImm64(
5669   MachineInstrBuilder &MIB, const MachineInstr &I, int OpIdx) const {
5670   assert(I.getOpcode() == TargetOpcode::G_CONSTANT && OpIdx == -1 &&
5671          "Expected G_CONSTANT");
5672   uint64_t CstVal = I.getOperand(1).getCImm()->getZExtValue();
5673   uint64_t Enc = AArch64_AM::encodeLogicalImmediate(CstVal, 64);
5674   MIB.addImm(Enc);
5675 }
5676 
5677 bool AArch64InstructionSelector::isLoadStoreOfNumBytes(
5678     const MachineInstr &MI, unsigned NumBytes) const {
5679   if (!MI.mayLoadOrStore())
5680     return false;
5681   assert(MI.hasOneMemOperand() &&
5682          "Expected load/store to have only one mem op!");
5683   return (*MI.memoperands_begin())->getSize() == NumBytes;
5684 }
5685 
5686 bool AArch64InstructionSelector::isDef32(const MachineInstr &MI) const {
5687   const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
5688   if (MRI.getType(MI.getOperand(0).getReg()).getSizeInBits() != 32)
5689     return false;
5690 
5691   // Only return true if we know the operation will zero-out the high half of
5692   // the 64-bit register. Truncates can be subregister copies, which don't
5693   // zero out the high bits. Copies and other copy-like instructions can be
5694   // fed by truncates, or could be lowered as subregister copies.
5695   switch (MI.getOpcode()) {
5696   default:
5697     return true;
5698   case TargetOpcode::COPY:
5699   case TargetOpcode::G_BITCAST:
5700   case TargetOpcode::G_TRUNC:
5701   case TargetOpcode::G_PHI:
5702     return false;
5703   }
5704 }
5705 
5706 
5707 // Perform fixups on the given PHI instruction's operands to force them all
5708 // to be the same as the destination regbank.
5709 static void fixupPHIOpBanks(MachineInstr &MI, MachineRegisterInfo &MRI,
5710                             const AArch64RegisterBankInfo &RBI) {
5711   assert(MI.getOpcode() == TargetOpcode::G_PHI && "Expected a G_PHI");
5712   Register DstReg = MI.getOperand(0).getReg();
5713   const RegisterBank *DstRB = MRI.getRegBankOrNull(DstReg);
5714   assert(DstRB && "Expected PHI dst to have regbank assigned");
5715   MachineIRBuilder MIB(MI);
5716 
5717   // Go through each operand and ensure it has the same regbank.
5718   for (unsigned OpIdx = 1; OpIdx < MI.getNumOperands(); ++OpIdx) {
5719     MachineOperand &MO = MI.getOperand(OpIdx);
5720     if (!MO.isReg())
5721       continue;
5722     Register OpReg = MO.getReg();
5723     const RegisterBank *RB = MRI.getRegBankOrNull(OpReg);
5724     if (RB != DstRB) {
5725       // Insert a cross-bank copy.
5726       auto *OpDef = MRI.getVRegDef(OpReg);
5727       const LLT &Ty = MRI.getType(OpReg);
5728       MIB.setInsertPt(*OpDef->getParent(), std::next(OpDef->getIterator()));
5729       auto Copy = MIB.buildCopy(Ty, OpReg);
5730       MRI.setRegBank(Copy.getReg(0), *DstRB);
5731       MO.setReg(Copy.getReg(0));
5732     }
5733   }
5734 }
5735 
5736 void AArch64InstructionSelector::processPHIs(MachineFunction &MF) {
5737   // We're looking for PHIs, build a list so we don't invalidate iterators.
5738   MachineRegisterInfo &MRI = MF.getRegInfo();
5739   SmallVector<MachineInstr *, 32> Phis;
5740   for (auto &BB : MF) {
5741     for (auto &MI : BB) {
5742       if (MI.getOpcode() == TargetOpcode::G_PHI)
5743         Phis.emplace_back(&MI);
5744     }
5745   }
5746 
5747   for (auto *MI : Phis) {
5748     // We need to do some work here if the operand types are < 16 bit and they
5749     // are split across fpr/gpr banks. Since all types <32b on gpr
5750     // end up being assigned gpr32 regclasses, we can end up with PHIs here
5751     // which try to select between a gpr32 and an fpr16. Ideally RBS shouldn't
5752     // be selecting heterogenous regbanks for operands if possible, but we
5753     // still need to be able to deal with it here.
5754     //
5755     // To fix this, if we have a gpr-bank operand < 32b in size and at least
5756     // one other operand is on the fpr bank, then we add cross-bank copies
5757     // to homogenize the operand banks. For simplicity the bank that we choose
5758     // to settle on is whatever bank the def operand has. For example:
5759     //
5760     // %endbb:
5761     //   %dst:gpr(s16) = G_PHI %in1:gpr(s16), %bb1, %in2:fpr(s16), %bb2
5762     //  =>
5763     // %bb2:
5764     //   ...
5765     //   %in2_copy:gpr(s16) = COPY %in2:fpr(s16)
5766     //   ...
5767     // %endbb:
5768     //   %dst:gpr(s16) = G_PHI %in1:gpr(s16), %bb1, %in2_copy:gpr(s16), %bb2
5769     bool HasGPROp = false, HasFPROp = false;
5770     for (unsigned OpIdx = 1; OpIdx < MI->getNumOperands(); ++OpIdx) {
5771       const auto &MO = MI->getOperand(OpIdx);
5772       if (!MO.isReg())
5773         continue;
5774       const LLT &Ty = MRI.getType(MO.getReg());
5775       if (!Ty.isValid() || !Ty.isScalar())
5776         break;
5777       if (Ty.getSizeInBits() >= 32)
5778         break;
5779       const RegisterBank *RB = MRI.getRegBankOrNull(MO.getReg());
5780       // If for some reason we don't have a regbank yet. Don't try anything.
5781       if (!RB)
5782         break;
5783 
5784       if (RB->getID() == AArch64::GPRRegBankID)
5785         HasGPROp = true;
5786       else
5787         HasFPROp = true;
5788     }
5789     // We have heterogenous regbanks, need to fixup.
5790     if (HasGPROp && HasFPROp)
5791       fixupPHIOpBanks(*MI, MRI, RBI);
5792   }
5793 }
5794 
5795 namespace llvm {
5796 InstructionSelector *
5797 createAArch64InstructionSelector(const AArch64TargetMachine &TM,
5798                                  AArch64Subtarget &Subtarget,
5799                                  AArch64RegisterBankInfo &RBI) {
5800   return new AArch64InstructionSelector(TM, Subtarget, RBI);
5801 }
5802 }
5803