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