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