1 //===- ARMISelLowering.h - ARM DAG Lowering Interface -----------*- 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 //
9 // This file defines the interfaces that ARM uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_LIB_TARGET_ARM_ARMISELLOWERING_H
15 #define LLVM_LIB_TARGET_ARM_ARMISELLOWERING_H
16 
17 #include "MCTargetDesc/ARMBaseInfo.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/CodeGen/CallingConvLower.h"
21 #include "llvm/CodeGen/ISDOpcodes.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/SelectionDAGNodes.h"
24 #include "llvm/CodeGen/TargetLowering.h"
25 #include "llvm/CodeGen/ValueTypes.h"
26 #include "llvm/IR/Attributes.h"
27 #include "llvm/IR/CallingConv.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/InlineAsm.h"
31 #include "llvm/Support/CodeGen.h"
32 #include "llvm/Support/MachineValueType.h"
33 #include <optional>
34 #include <utility>
35 
36 namespace llvm {
37 
38 class ARMSubtarget;
39 class DataLayout;
40 class FastISel;
41 class FunctionLoweringInfo;
42 class GlobalValue;
43 class InstrItineraryData;
44 class Instruction;
45 class MachineBasicBlock;
46 class MachineInstr;
47 class SelectionDAG;
48 class TargetLibraryInfo;
49 class TargetMachine;
50 class TargetRegisterInfo;
51 class VectorType;
52 
53   namespace ARMISD {
54 
55   // ARM Specific DAG Nodes
56   enum NodeType : unsigned {
57     // Start the numbering where the builtin ops and target ops leave off.
58     FIRST_NUMBER = ISD::BUILTIN_OP_END,
59 
60     Wrapper,    // Wrapper - A wrapper node for TargetConstantPool,
61                 // TargetExternalSymbol, and TargetGlobalAddress.
62     WrapperPIC, // WrapperPIC - A wrapper node for TargetGlobalAddress in
63                 // PIC mode.
64     WrapperJT,  // WrapperJT - A wrapper node for TargetJumpTable
65 
66     // Add pseudo op to model memcpy for struct byval.
67     COPY_STRUCT_BYVAL,
68 
69     CALL,        // Function call.
70     CALL_PRED,   // Function call that's predicable.
71     CALL_NOLINK, // Function call with branch not branch-and-link.
72     tSECALL,     // CMSE non-secure function call.
73     t2CALL_BTI,  // Thumb function call followed by BTI instruction.
74     BRCOND,      // Conditional branch.
75     BR_JT,       // Jumptable branch.
76     BR2_JT,      // Jumptable branch (2 level - jumptable entry is a jump).
77     RET_FLAG,    // Return with a flag operand.
78     SERET_FLAG,  // CMSE Entry function return with a flag operand.
79     INTRET_FLAG, // Interrupt return with an LR-offset and a flag operand.
80 
81     PIC_ADD, // Add with a PC operand and a PIC label.
82 
83     ASRL, // MVE long arithmetic shift right.
84     LSRL, // MVE long shift right.
85     LSLL, // MVE long shift left.
86 
87     CMP,      // ARM compare instructions.
88     CMN,      // ARM CMN instructions.
89     CMPZ,     // ARM compare that sets only Z flag.
90     CMPFP,    // ARM VFP compare instruction, sets FPSCR.
91     CMPFPE,   // ARM VFP signalling compare instruction, sets FPSCR.
92     CMPFPw0,  // ARM VFP compare against zero instruction, sets FPSCR.
93     CMPFPEw0, // ARM VFP signalling compare against zero instruction, sets
94               // FPSCR.
95     FMSTAT,   // ARM fmstat instruction.
96 
97     CMOV, // ARM conditional move instructions.
98     SUBS, // Flag-setting subtraction.
99 
100     SSAT, // Signed saturation
101     USAT, // Unsigned saturation
102 
103     BCC_i64,
104 
105     SRL_FLAG, // V,Flag = srl_flag X -> srl X, 1 + save carry out.
106     SRA_FLAG, // V,Flag = sra_flag X -> sra X, 1 + save carry out.
107     RRX,      // V = RRX X, Flag     -> srl X, 1 + shift in carry flag.
108 
109     ADDC, // Add with carry
110     ADDE, // Add using carry
111     SUBC, // Sub with carry
112     SUBE, // Sub using carry
113     LSLS, // Shift left producing carry
114 
115     VMOVRRD, // double to two gprs.
116     VMOVDRR, // Two gprs to double.
117     VMOVSR,  // move gpr to single, used for f32 literal constructed in a gpr
118 
119     EH_SJLJ_SETJMP,         // SjLj exception handling setjmp.
120     EH_SJLJ_LONGJMP,        // SjLj exception handling longjmp.
121     EH_SJLJ_SETUP_DISPATCH, // SjLj exception handling setup_dispatch.
122 
123     TC_RETURN, // Tail call return pseudo.
124 
125     THREAD_POINTER,
126 
127     DYN_ALLOC, // Dynamic allocation on the stack.
128 
129     MEMBARRIER_MCR, // Memory barrier (MCR)
130 
131     PRELOAD, // Preload
132 
133     WIN__CHKSTK, // Windows' __chkstk call to do stack probing.
134     WIN__DBZCHK, // Windows' divide by zero check
135 
136     WLS, // Low-overhead loops, While Loop Start branch. See t2WhileLoopStart
137     WLSSETUP, // Setup for the iteration count of a WLS. See t2WhileLoopSetup.
138     LOOP_DEC, // Really a part of LE, performs the sub
139     LE,       // Low-overhead loops, Loop End
140 
141     PREDICATE_CAST,  // Predicate cast for MVE i1 types
142     VECTOR_REG_CAST, // Reinterpret the current contents of a vector register
143 
144     MVESEXT,  // Legalization aids for extending a vector into two/four vectors.
145     MVEZEXT,  //  or truncating two/four vectors into one. Eventually becomes
146     MVETRUNC, //  stack store/load sequence, if not optimized to anything else.
147 
148     VCMP,  // Vector compare.
149     VCMPZ, // Vector compare to zero.
150     VTST,  // Vector test bits.
151 
152     // Vector shift by vector
153     VSHLs, // ...left/right by signed
154     VSHLu, // ...left/right by unsigned
155 
156     // Vector shift by immediate:
157     VSHLIMM,  // ...left
158     VSHRsIMM, // ...right (signed)
159     VSHRuIMM, // ...right (unsigned)
160 
161     // Vector rounding shift by immediate:
162     VRSHRsIMM, // ...right (signed)
163     VRSHRuIMM, // ...right (unsigned)
164     VRSHRNIMM, // ...right narrow
165 
166     // Vector saturating shift by immediate:
167     VQSHLsIMM,   // ...left (signed)
168     VQSHLuIMM,   // ...left (unsigned)
169     VQSHLsuIMM,  // ...left (signed to unsigned)
170     VQSHRNsIMM,  // ...right narrow (signed)
171     VQSHRNuIMM,  // ...right narrow (unsigned)
172     VQSHRNsuIMM, // ...right narrow (signed to unsigned)
173 
174     // Vector saturating rounding shift by immediate:
175     VQRSHRNsIMM,  // ...right narrow (signed)
176     VQRSHRNuIMM,  // ...right narrow (unsigned)
177     VQRSHRNsuIMM, // ...right narrow (signed to unsigned)
178 
179     // Vector shift and insert:
180     VSLIIMM, // ...left
181     VSRIIMM, // ...right
182 
183     // Vector get lane (VMOV scalar to ARM core register)
184     // (These are used for 8- and 16-bit element types only.)
185     VGETLANEu, // zero-extend vector extract element
186     VGETLANEs, // sign-extend vector extract element
187 
188     // Vector move immediate and move negated immediate:
189     VMOVIMM,
190     VMVNIMM,
191 
192     // Vector move f32 immediate:
193     VMOVFPIMM,
194 
195     // Move H <-> R, clearing top 16 bits
196     VMOVrh,
197     VMOVhr,
198 
199     // Vector duplicate:
200     VDUP,
201     VDUPLANE,
202 
203     // Vector shuffles:
204     VEXT,   // extract
205     VREV64, // reverse elements within 64-bit doublewords
206     VREV32, // reverse elements within 32-bit words
207     VREV16, // reverse elements within 16-bit halfwords
208     VZIP,   // zip (interleave)
209     VUZP,   // unzip (deinterleave)
210     VTRN,   // transpose
211     VTBL1,  // 1-register shuffle with mask
212     VTBL2,  // 2-register shuffle with mask
213     VMOVN,  // MVE vmovn
214 
215     // MVE Saturating truncates
216     VQMOVNs, // Vector (V) Saturating (Q) Move and Narrow (N), signed (s)
217     VQMOVNu, // Vector (V) Saturating (Q) Move and Narrow (N), unsigned (u)
218 
219     // MVE float <> half converts
220     VCVTN, // MVE vcvt f32 -> f16, truncating into either the bottom or top
221            // lanes
222     VCVTL, // MVE vcvt f16 -> f32, extending from either the bottom or top lanes
223 
224     // MVE VIDUP instruction, taking a start value and increment.
225     VIDUP,
226 
227     // Vector multiply long:
228     VMULLs, // ...signed
229     VMULLu, // ...unsigned
230 
231     VQDMULH, // MVE vqdmulh instruction
232 
233     // MVE reductions
234     VADDVs,  // sign- or zero-extend the elements of a vector to i32,
235     VADDVu,  //   add them all together, and return an i32 of their sum
236     VADDVps, // Same as VADDV[su] but with a v4i1 predicate mask
237     VADDVpu,
238     VADDLVs,  // sign- or zero-extend elements to i64 and sum, returning
239     VADDLVu,  //   the low and high 32-bit halves of the sum
240     VADDLVAs, // Same as VADDLV[su] but also add an input accumulator
241     VADDLVAu, //   provided as low and high halves
242     VADDLVps, // Same as VADDLV[su] but with a v4i1 predicate mask
243     VADDLVpu,
244     VADDLVAps, // Same as VADDLVp[su] but with a v4i1 predicate mask
245     VADDLVApu,
246     VMLAVs, // sign- or zero-extend the elements of two vectors to i32, multiply
247             // them
248     VMLAVu, //   and add the results together, returning an i32 of their sum
249     VMLAVps, // Same as VMLAV[su] with a v4i1 predicate mask
250     VMLAVpu,
251     VMLALVs,  // Same as VMLAV but with i64, returning the low and
252     VMLALVu,  //   high 32-bit halves of the sum
253     VMLALVps, // Same as VMLALV[su] with a v4i1 predicate mask
254     VMLALVpu,
255     VMLALVAs,  // Same as VMLALV but also add an input accumulator
256     VMLALVAu,  //   provided as low and high halves
257     VMLALVAps, // Same as VMLALVA[su] with a v4i1 predicate mask
258     VMLALVApu,
259     VMINVu, // Find minimum unsigned value of a vector and register
260     VMINVs, // Find minimum signed value of a vector and register
261     VMAXVu, // Find maximum unsigned value of a vector and register
262     VMAXVs, // Find maximum signed value of a vector and register
263 
264     SMULWB,  // Signed multiply word by half word, bottom
265     SMULWT,  // Signed multiply word by half word, top
266     UMLAL,   // 64bit Unsigned Accumulate Multiply
267     SMLAL,   // 64bit Signed Accumulate Multiply
268     UMAAL,   // 64-bit Unsigned Accumulate Accumulate Multiply
269     SMLALBB, // 64-bit signed accumulate multiply bottom, bottom 16
270     SMLALBT, // 64-bit signed accumulate multiply bottom, top 16
271     SMLALTB, // 64-bit signed accumulate multiply top, bottom 16
272     SMLALTT, // 64-bit signed accumulate multiply top, top 16
273     SMLALD,  // Signed multiply accumulate long dual
274     SMLALDX, // Signed multiply accumulate long dual exchange
275     SMLSLD,  // Signed multiply subtract long dual
276     SMLSLDX, // Signed multiply subtract long dual exchange
277     SMMLAR,  // Signed multiply long, round and add
278     SMMLSR,  // Signed multiply long, subtract and round
279 
280     // Single Lane QADD8 and QADD16. Only the bottom lane. That's what the b
281     // stands for.
282     QADD8b,
283     QSUB8b,
284     QADD16b,
285     QSUB16b,
286     UQADD8b,
287     UQSUB8b,
288     UQADD16b,
289     UQSUB16b,
290 
291     // Operands of the standard BUILD_VECTOR node are not legalized, which
292     // is fine if BUILD_VECTORs are always lowered to shuffles or other
293     // operations, but for ARM some BUILD_VECTORs are legal as-is and their
294     // operands need to be legalized.  Define an ARM-specific version of
295     // BUILD_VECTOR for this purpose.
296     BUILD_VECTOR,
297 
298     // Bit-field insert
299     BFI,
300 
301     // Vector OR with immediate
302     VORRIMM,
303     // Vector AND with NOT of immediate
304     VBICIMM,
305 
306     // Pseudo vector bitwise select
307     VBSP,
308 
309     // Pseudo-instruction representing a memory copy using ldm/stm
310     // instructions.
311     MEMCPY,
312 
313     // Pseudo-instruction representing a memory copy using a tail predicated
314     // loop
315     MEMCPYLOOP,
316     // Pseudo-instruction representing a memset using a tail predicated
317     // loop
318     MEMSETLOOP,
319 
320     // V8.1MMainline condition select
321     CSINV, // Conditional select invert.
322     CSNEG, // Conditional select negate.
323     CSINC, // Conditional select increment.
324 
325     // Vector load N-element structure to all lanes:
326     VLD1DUP = ISD::FIRST_TARGET_MEMORY_OPCODE,
327     VLD2DUP,
328     VLD3DUP,
329     VLD4DUP,
330 
331     // NEON loads with post-increment base updates:
332     VLD1_UPD,
333     VLD2_UPD,
334     VLD3_UPD,
335     VLD4_UPD,
336     VLD2LN_UPD,
337     VLD3LN_UPD,
338     VLD4LN_UPD,
339     VLD1DUP_UPD,
340     VLD2DUP_UPD,
341     VLD3DUP_UPD,
342     VLD4DUP_UPD,
343     VLD1x2_UPD,
344     VLD1x3_UPD,
345     VLD1x4_UPD,
346 
347     // NEON stores with post-increment base updates:
348     VST1_UPD,
349     VST2_UPD,
350     VST3_UPD,
351     VST4_UPD,
352     VST2LN_UPD,
353     VST3LN_UPD,
354     VST4LN_UPD,
355     VST1x2_UPD,
356     VST1x3_UPD,
357     VST1x4_UPD,
358 
359     // Load/Store of dual registers
360     LDRD,
361     STRD
362   };
363 
364   } // end namespace ARMISD
365 
366   namespace ARM {
367   /// Possible values of current rounding mode, which is specified in bits
368   /// 23:22 of FPSCR.
369   enum Rounding {
370     RN = 0,    // Round to Nearest
371     RP = 1,    // Round towards Plus infinity
372     RM = 2,    // Round towards Minus infinity
373     RZ = 3,    // Round towards Zero
374     rmMask = 3 // Bit mask selecting rounding mode
375   };
376 
377   // Bit position of rounding mode bits in FPSCR.
378   const unsigned RoundingBitsPos = 22;
379   } // namespace ARM
380 
381   /// Define some predicates that are used for node matching.
382   namespace ARM {
383 
384     bool isBitFieldInvertedMask(unsigned v);
385 
386   } // end namespace ARM
387 
388   //===--------------------------------------------------------------------===//
389   //  ARMTargetLowering - ARM Implementation of the TargetLowering interface
390 
391   class ARMTargetLowering : public TargetLowering {
392   public:
393     explicit ARMTargetLowering(const TargetMachine &TM,
394                                const ARMSubtarget &STI);
395 
396     unsigned getJumpTableEncoding() const override;
397     bool useSoftFloat() const override;
398 
399     SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override;
400 
401     /// ReplaceNodeResults - Replace the results of node with an illegal result
402     /// type with new values built out of custom code.
403     void ReplaceNodeResults(SDNode *N, SmallVectorImpl<SDValue>&Results,
404                             SelectionDAG &DAG) const override;
405 
406     const char *getTargetNodeName(unsigned Opcode) const override;
407 
408     bool isSelectSupported(SelectSupportKind Kind) const override {
409       // ARM does not support scalar condition selects on vectors.
410       return (Kind != ScalarCondVectorVal);
411     }
412 
413     bool isReadOnly(const GlobalValue *GV) const;
414 
415     /// getSetCCResultType - Return the value type to use for ISD::SETCC.
416     EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context,
417                            EVT VT) const override;
418 
419     MachineBasicBlock *
420     EmitInstrWithCustomInserter(MachineInstr &MI,
421                                 MachineBasicBlock *MBB) const override;
422 
423     void AdjustInstrPostInstrSelection(MachineInstr &MI,
424                                        SDNode *Node) const override;
425 
426     SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const;
427     SDValue PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const;
428     SDValue PerformCMOVToBFICombine(SDNode *N, SelectionDAG &DAG) const;
429     SDValue PerformIntrinsicCombine(SDNode *N, DAGCombinerInfo &DCI) const;
430     SDValue PerformMVEExtCombine(SDNode *N, DAGCombinerInfo &DCI) const;
431     SDValue PerformMVETruncCombine(SDNode *N, DAGCombinerInfo &DCI) const;
432     SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override;
433 
434     bool SimplifyDemandedBitsForTargetNode(SDValue Op,
435                                            const APInt &OriginalDemandedBits,
436                                            const APInt &OriginalDemandedElts,
437                                            KnownBits &Known,
438                                            TargetLoweringOpt &TLO,
439                                            unsigned Depth) const override;
440 
441     bool isDesirableToTransformToIntegerOp(unsigned Opc, EVT VT) const override;
442 
443     /// allowsMisalignedMemoryAccesses - Returns true if the target allows
444     /// unaligned memory accesses of the specified type. Returns whether it
445     /// is "fast" by reference in the second argument.
446     bool allowsMisalignedMemoryAccesses(EVT VT, unsigned AddrSpace,
447                                         Align Alignment,
448                                         MachineMemOperand::Flags Flags,
449                                         unsigned *Fast) const override;
450 
451     EVT getOptimalMemOpType(const MemOp &Op,
452                             const AttributeList &FuncAttributes) const override;
453 
454     bool isTruncateFree(Type *SrcTy, Type *DstTy) const override;
455     bool isTruncateFree(EVT SrcVT, EVT DstVT) const override;
456     bool isZExtFree(SDValue Val, EVT VT2) const override;
457     bool shouldSinkOperands(Instruction *I,
458                             SmallVectorImpl<Use *> &Ops) const override;
459     Type* shouldConvertSplatType(ShuffleVectorInst* SVI) const override;
460 
461     bool isFNegFree(EVT VT) const override;
462 
463     bool isVectorLoadExtDesirable(SDValue ExtVal) const override;
464 
465     bool allowTruncateForTailCall(Type *Ty1, Type *Ty2) const override;
466 
467 
468     /// isLegalAddressingMode - Return true if the addressing mode represented
469     /// by AM is legal for this target, for a load/store of the specified type.
470     bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM,
471                                Type *Ty, unsigned AS,
472                                Instruction *I = nullptr) const override;
473 
474     bool isLegalT2ScaledAddressingMode(const AddrMode &AM, EVT VT) const;
475 
476     /// Returns true if the addressing mode representing by AM is legal
477     /// for the Thumb1 target, for a load/store of the specified type.
478     bool isLegalT1ScaledAddressingMode(const AddrMode &AM, EVT VT) const;
479 
480     /// isLegalICmpImmediate - Return true if the specified immediate is legal
481     /// icmp immediate, that is the target has icmp instructions which can
482     /// compare a register against the immediate without having to materialize
483     /// the immediate into a register.
484     bool isLegalICmpImmediate(int64_t Imm) const override;
485 
486     /// isLegalAddImmediate - Return true if the specified immediate is legal
487     /// add immediate, that is the target has add instructions which can
488     /// add a register and the immediate without having to materialize
489     /// the immediate into a register.
490     bool isLegalAddImmediate(int64_t Imm) const override;
491 
492     /// getPreIndexedAddressParts - returns true by value, base pointer and
493     /// offset pointer and addressing mode by reference if the node's address
494     /// can be legally represented as pre-indexed load / store address.
495     bool getPreIndexedAddressParts(SDNode *N, SDValue &Base, SDValue &Offset,
496                                    ISD::MemIndexedMode &AM,
497                                    SelectionDAG &DAG) const override;
498 
499     /// getPostIndexedAddressParts - returns true by value, base pointer and
500     /// offset pointer and addressing mode by reference if this node can be
501     /// combined with a load / store to form a post-indexed load / store.
502     bool getPostIndexedAddressParts(SDNode *N, SDNode *Op, SDValue &Base,
503                                     SDValue &Offset, ISD::MemIndexedMode &AM,
504                                     SelectionDAG &DAG) const override;
505 
506     void computeKnownBitsForTargetNode(const SDValue Op, KnownBits &Known,
507                                        const APInt &DemandedElts,
508                                        const SelectionDAG &DAG,
509                                        unsigned Depth) const override;
510 
511     bool targetShrinkDemandedConstant(SDValue Op, const APInt &DemandedBits,
512                                       const APInt &DemandedElts,
513                                       TargetLoweringOpt &TLO) const override;
514 
515     bool ExpandInlineAsm(CallInst *CI) const override;
516 
517     ConstraintType getConstraintType(StringRef Constraint) const override;
518 
519     /// Examine constraint string and operand type and determine a weight value.
520     /// The operand object must already have been set up with the operand type.
521     ConstraintWeight getSingleConstraintMatchWeight(
522       AsmOperandInfo &info, const char *constraint) const override;
523 
524     std::pair<unsigned, const TargetRegisterClass *>
525     getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
526                                  StringRef Constraint, MVT VT) const override;
527 
528     const char *LowerXConstraint(EVT ConstraintVT) const override;
529 
530     /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
531     /// vector.  If it is invalid, don't add anything to Ops. If hasMemory is
532     /// true it means one of the asm constraint of the inline asm instruction
533     /// being processed is 'm'.
534     void LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint,
535                                       std::vector<SDValue> &Ops,
536                                       SelectionDAG &DAG) const override;
537 
538     unsigned
539     getInlineAsmMemConstraint(StringRef ConstraintCode) const override {
540       if (ConstraintCode == "Q")
541         return InlineAsm::Constraint_Q;
542       else if (ConstraintCode.size() == 2) {
543         if (ConstraintCode[0] == 'U') {
544           switch(ConstraintCode[1]) {
545           default:
546             break;
547           case 'm':
548             return InlineAsm::Constraint_Um;
549           case 'n':
550             return InlineAsm::Constraint_Un;
551           case 'q':
552             return InlineAsm::Constraint_Uq;
553           case 's':
554             return InlineAsm::Constraint_Us;
555           case 't':
556             return InlineAsm::Constraint_Ut;
557           case 'v':
558             return InlineAsm::Constraint_Uv;
559           case 'y':
560             return InlineAsm::Constraint_Uy;
561           }
562         }
563       }
564       return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
565     }
566 
567     const ARMSubtarget* getSubtarget() const {
568       return Subtarget;
569     }
570 
571     /// getRegClassFor - Return the register class that should be used for the
572     /// specified value type.
573     const TargetRegisterClass *
574     getRegClassFor(MVT VT, bool isDivergent = false) const override;
575 
576     bool shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
577                                 Align &PrefAlign) const override;
578 
579     /// createFastISel - This method returns a target specific FastISel object,
580     /// or null if the target does not support "fast" ISel.
581     FastISel *createFastISel(FunctionLoweringInfo &funcInfo,
582                              const TargetLibraryInfo *libInfo) const override;
583 
584     Sched::Preference getSchedulingPreference(SDNode *N) const override;
585 
586     bool preferZeroCompareBranch() const override { return true; }
587 
588     bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const override;
589 
590     bool
591     isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const override;
592     bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const override;
593 
594     /// isFPImmLegal - Returns true if the target can instruction select the
595     /// specified FP immediate natively. If false, the legalizer will
596     /// materialize the FP immediate as a load from a constant pool.
597     bool isFPImmLegal(const APFloat &Imm, EVT VT,
598                       bool ForCodeSize = false) const override;
599 
600     bool getTgtMemIntrinsic(IntrinsicInfo &Info,
601                             const CallInst &I,
602                             MachineFunction &MF,
603                             unsigned Intrinsic) const override;
604 
605     /// Returns true if it is beneficial to convert a load of a constant
606     /// to just the constant itself.
607     bool shouldConvertConstantLoadToIntImm(const APInt &Imm,
608                                            Type *Ty) const override;
609 
610     /// Return true if EXTRACT_SUBVECTOR is cheap for this result type
611     /// with this index.
612     bool isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
613                                  unsigned Index) const override;
614 
615     bool shouldFormOverflowOp(unsigned Opcode, EVT VT,
616                               bool MathUsed) const override {
617       // Using overflow ops for overflow checks only should beneficial on ARM.
618       return TargetLowering::shouldFormOverflowOp(Opcode, VT, true);
619     }
620 
621     /// Returns true if an argument of type Ty needs to be passed in a
622     /// contiguous block of registers in calling convention CallConv.
623     bool functionArgumentNeedsConsecutiveRegisters(
624         Type *Ty, CallingConv::ID CallConv, bool isVarArg,
625         const DataLayout &DL) const override;
626 
627     /// If a physical register, this returns the register that receives the
628     /// exception address on entry to an EH pad.
629     Register
630     getExceptionPointerRegister(const Constant *PersonalityFn) const override;
631 
632     /// If a physical register, this returns the register that receives the
633     /// exception typeid on entry to a landing pad.
634     Register
635     getExceptionSelectorRegister(const Constant *PersonalityFn) const override;
636 
637     Instruction *makeDMB(IRBuilderBase &Builder, ARM_MB::MemBOpt Domain) const;
638     Value *emitLoadLinked(IRBuilderBase &Builder, Type *ValueTy, Value *Addr,
639                           AtomicOrdering Ord) const override;
640     Value *emitStoreConditional(IRBuilderBase &Builder, Value *Val, Value *Addr,
641                                 AtomicOrdering Ord) const override;
642 
643     void
644     emitAtomicCmpXchgNoStoreLLBalance(IRBuilderBase &Builder) const override;
645 
646     Instruction *emitLeadingFence(IRBuilderBase &Builder, Instruction *Inst,
647                                   AtomicOrdering Ord) const override;
648     Instruction *emitTrailingFence(IRBuilderBase &Builder, Instruction *Inst,
649                                    AtomicOrdering Ord) const override;
650 
651     unsigned getMaxSupportedInterleaveFactor() const override;
652 
653     bool lowerInterleavedLoad(LoadInst *LI,
654                               ArrayRef<ShuffleVectorInst *> Shuffles,
655                               ArrayRef<unsigned> Indices,
656                               unsigned Factor) const override;
657     bool lowerInterleavedStore(StoreInst *SI, ShuffleVectorInst *SVI,
658                                unsigned Factor) const override;
659 
660     bool shouldInsertFencesForAtomic(const Instruction *I) const override;
661     TargetLoweringBase::AtomicExpansionKind
662     shouldExpandAtomicLoadInIR(LoadInst *LI) const override;
663     TargetLoweringBase::AtomicExpansionKind
664     shouldExpandAtomicStoreInIR(StoreInst *SI) const override;
665     TargetLoweringBase::AtomicExpansionKind
666     shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const override;
667     TargetLoweringBase::AtomicExpansionKind
668     shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const override;
669 
670     bool useLoadStackGuardNode() const override;
671 
672     void insertSSPDeclarations(Module &M) const override;
673     Value *getSDagStackGuard(const Module &M) const override;
674     Function *getSSPStackGuardCheck(const Module &M) const override;
675 
676     bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
677                                    unsigned &Cost) const override;
678 
679     bool canMergeStoresTo(unsigned AddressSpace, EVT MemVT,
680                           const MachineFunction &MF) const override {
681       // Do not merge to larger than i32.
682       return (MemVT.getSizeInBits() <= 32);
683     }
684 
685     bool isCheapToSpeculateCttz(Type *Ty) const override;
686     bool isCheapToSpeculateCtlz(Type *Ty) const override;
687 
688     bool convertSetCCLogicToBitwiseLogic(EVT VT) const override {
689       return VT.isScalarInteger();
690     }
691 
692     bool supportSwiftError() const override {
693       return true;
694     }
695 
696     bool hasStandaloneRem(EVT VT) const override {
697       return HasStandaloneRem;
698     }
699 
700     ShiftLegalizationStrategy
701     preferredShiftLegalizationStrategy(SelectionDAG &DAG, SDNode *N,
702                                        unsigned ExpansionFactor) const override;
703 
704     CCAssignFn *CCAssignFnForCall(CallingConv::ID CC, bool isVarArg) const;
705     CCAssignFn *CCAssignFnForReturn(CallingConv::ID CC, bool isVarArg) const;
706 
707     /// Returns true if \p VecTy is a legal interleaved access type. This
708     /// function checks the vector element type and the overall width of the
709     /// vector.
710     bool isLegalInterleavedAccessType(unsigned Factor, FixedVectorType *VecTy,
711                                       Align Alignment,
712                                       const DataLayout &DL) const;
713 
714     bool isMulAddWithConstProfitable(SDValue AddNode,
715                                      SDValue ConstNode) const override;
716 
717     bool alignLoopsWithOptSize() const override;
718 
719     /// Returns the number of interleaved accesses that will be generated when
720     /// lowering accesses of the given type.
721     unsigned getNumInterleavedAccesses(VectorType *VecTy,
722                                        const DataLayout &DL) const;
723 
724     void finalizeLowering(MachineFunction &MF) const override;
725 
726     /// Return the correct alignment for the current calling convention.
727     Align getABIAlignmentForCallingConv(Type *ArgTy,
728                                         const DataLayout &DL) const override;
729 
730     bool isDesirableToCommuteWithShift(const SDNode *N,
731                                        CombineLevel Level) const override;
732 
733     bool isDesirableToCommuteXorWithShift(const SDNode *N) const override;
734 
735     bool shouldFoldConstantShiftPairToMask(const SDNode *N,
736                                            CombineLevel Level) const override;
737 
738     bool preferIncOfAddToSubOfNot(EVT VT) const override;
739 
740     bool shouldConvertFpToSat(unsigned Op, EVT FPVT, EVT VT) const override;
741 
742     bool isComplexDeinterleavingSupported() const override;
743     bool isComplexDeinterleavingOperationSupported(
744         ComplexDeinterleavingOperation Operation, Type *Ty) const override;
745 
746     Value *createComplexDeinterleavingIR(
747         Instruction *I, ComplexDeinterleavingOperation OperationType,
748         ComplexDeinterleavingRotation Rotation, Value *InputA, Value *InputB,
749         Value *Accumulator = nullptr) const override;
750 
751   protected:
752     std::pair<const TargetRegisterClass *, uint8_t>
753     findRepresentativeClass(const TargetRegisterInfo *TRI,
754                             MVT VT) const override;
755 
756   private:
757     /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
758     /// make the right decision when generating code for different targets.
759     const ARMSubtarget *Subtarget;
760 
761     const TargetRegisterInfo *RegInfo;
762 
763     const InstrItineraryData *Itins;
764 
765     /// ARMPCLabelIndex - Keep track of the number of ARM PC labels created.
766     unsigned ARMPCLabelIndex;
767 
768     // TODO: remove this, and have shouldInsertFencesForAtomic do the proper
769     // check.
770     bool InsertFencesForAtomic;
771 
772     bool HasStandaloneRem = true;
773 
774     void addTypeForNEON(MVT VT, MVT PromotedLdStVT);
775     void addDRTypeForNEON(MVT VT);
776     void addQRTypeForNEON(MVT VT);
777     std::pair<SDValue, SDValue> getARMXALUOOp(SDValue Op, SelectionDAG &DAG, SDValue &ARMcc) const;
778 
779     using RegsToPassVector = SmallVector<std::pair<unsigned, SDValue>, 8>;
780 
781     void PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG, SDValue Chain,
782                           SDValue &Arg, RegsToPassVector &RegsToPass,
783                           CCValAssign &VA, CCValAssign &NextVA,
784                           SDValue &StackPtr,
785                           SmallVectorImpl<SDValue> &MemOpChains,
786                           bool IsTailCall,
787                           int SPDiff) const;
788     SDValue GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
789                                  SDValue &Root, SelectionDAG &DAG,
790                                  const SDLoc &dl) const;
791 
792     CallingConv::ID getEffectiveCallingConv(CallingConv::ID CC,
793                                             bool isVarArg) const;
794     CCAssignFn *CCAssignFnForNode(CallingConv::ID CC, bool Return,
795                                   bool isVarArg) const;
796     std::pair<SDValue, MachinePointerInfo>
797     computeAddrForCallArg(const SDLoc &dl, SelectionDAG &DAG,
798                           const CCValAssign &VA, SDValue StackPtr,
799                           bool IsTailCall, int SPDiff) const;
800     SDValue LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const;
801     SDValue LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const;
802     SDValue LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op, SelectionDAG &DAG) const;
803     SDValue LowerINTRINSIC_VOID(SDValue Op, SelectionDAG &DAG,
804                                     const ARMSubtarget *Subtarget) const;
805     SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
806                                     const ARMSubtarget *Subtarget) const;
807     SDValue LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const;
808     SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) const;
809     SDValue LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const;
810     SDValue LowerGlobalAddressDarwin(SDValue Op, SelectionDAG &DAG) const;
811     SDValue LowerGlobalAddressELF(SDValue Op, SelectionDAG &DAG) const;
812     SDValue LowerGlobalAddressWindows(SDValue Op, SelectionDAG &DAG) const;
813     SDValue LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const;
814     SDValue LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
815                                             SelectionDAG &DAG) const;
816     SDValue LowerToTLSExecModels(GlobalAddressSDNode *GA,
817                                  SelectionDAG &DAG,
818                                  TLSModel::Model model) const;
819     SDValue LowerGlobalTLSAddressDarwin(SDValue Op, SelectionDAG &DAG) const;
820     SDValue LowerGlobalTLSAddressWindows(SDValue Op, SelectionDAG &DAG) const;
821     SDValue LowerGLOBAL_OFFSET_TABLE(SDValue Op, SelectionDAG &DAG) const;
822     SDValue LowerBR_JT(SDValue Op, SelectionDAG &DAG) const;
823     SDValue LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const;
824     SDValue LowerUnsignedALUO(SDValue Op, SelectionDAG &DAG) const;
825     SDValue LowerSELECT(SDValue Op, SelectionDAG &DAG) const;
826     SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const;
827     SDValue LowerBRCOND(SDValue Op, SelectionDAG &DAG) const;
828     SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG) const;
829     SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const;
830     SDValue LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const;
831     SDValue LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const;
832     SDValue LowerShiftRightParts(SDValue Op, SelectionDAG &DAG) const;
833     SDValue LowerShiftLeftParts(SDValue Op, SelectionDAG &DAG) const;
834     SDValue LowerGET_ROUNDING(SDValue Op, SelectionDAG &DAG) const;
835     SDValue LowerSET_ROUNDING(SDValue Op, SelectionDAG &DAG) const;
836     SDValue LowerConstantFP(SDValue Op, SelectionDAG &DAG,
837                             const ARMSubtarget *ST) const;
838     SDValue LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
839                               const ARMSubtarget *ST) const;
840     SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const;
841     SDValue LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const;
842     SDValue LowerDivRem(SDValue Op, SelectionDAG &DAG) const;
843     SDValue LowerDIV_Windows(SDValue Op, SelectionDAG &DAG, bool Signed) const;
844     void ExpandDIV_Windows(SDValue Op, SelectionDAG &DAG, bool Signed,
845                            SmallVectorImpl<SDValue> &Results) const;
846     SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
847                           const ARMSubtarget *Subtarget) const;
848     SDValue LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG, bool Signed,
849                                    SDValue &Chain) const;
850     SDValue LowerREM(SDNode *N, SelectionDAG &DAG) const;
851     SDValue LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const;
852     SDValue LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const;
853     SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const;
854     SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const;
855     SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const;
856     SDValue LowerFSETCC(SDValue Op, SelectionDAG &DAG) const;
857     SDValue LowerSPONENTRY(SDValue Op, SelectionDAG &DAG) const;
858     void LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results,
859                    SelectionDAG &DAG) const;
860 
861     Register getRegisterByName(const char* RegName, LLT VT,
862                                const MachineFunction &MF) const override;
863 
864     SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
865                           SmallVectorImpl<SDNode *> &Created) const override;
866 
867     bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
868                                     EVT VT) const override;
869 
870     SDValue MoveToHPR(const SDLoc &dl, SelectionDAG &DAG, MVT LocVT, MVT ValVT,
871                       SDValue Val) const;
872     SDValue MoveFromHPR(const SDLoc &dl, SelectionDAG &DAG, MVT LocVT,
873                         MVT ValVT, SDValue Val) const;
874 
875     SDValue ReconstructShuffle(SDValue Op, SelectionDAG &DAG) const;
876 
877     SDValue LowerCallResult(SDValue Chain, SDValue InFlag,
878                             CallingConv::ID CallConv, bool isVarArg,
879                             const SmallVectorImpl<ISD::InputArg> &Ins,
880                             const SDLoc &dl, SelectionDAG &DAG,
881                             SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
882                             SDValue ThisVal) const;
883 
884     bool supportSplitCSR(MachineFunction *MF) const override {
885       return MF->getFunction().getCallingConv() == CallingConv::CXX_FAST_TLS &&
886           MF->getFunction().hasFnAttribute(Attribute::NoUnwind);
887     }
888 
889     void initializeSplitCSR(MachineBasicBlock *Entry) const override;
890     void insertCopiesSplitCSR(
891       MachineBasicBlock *Entry,
892       const SmallVectorImpl<MachineBasicBlock *> &Exits) const override;
893 
894     bool splitValueIntoRegisterParts(
895         SelectionDAG & DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
896         unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC)
897         const override;
898 
899     SDValue joinRegisterPartsIntoValue(
900         SelectionDAG & DAG, const SDLoc &DL, const SDValue *Parts,
901         unsigned NumParts, MVT PartVT, EVT ValueVT,
902         std::optional<CallingConv::ID> CC) const override;
903 
904     SDValue
905     LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
906                          const SmallVectorImpl<ISD::InputArg> &Ins,
907                          const SDLoc &dl, SelectionDAG &DAG,
908                          SmallVectorImpl<SDValue> &InVals) const override;
909 
910     int StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG, const SDLoc &dl,
911                        SDValue &Chain, const Value *OrigArg,
912                        unsigned InRegsParamRecordIdx, int ArgOffset,
913                        unsigned ArgSize) const;
914 
915     void VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
916                               const SDLoc &dl, SDValue &Chain,
917                               unsigned ArgOffset, unsigned TotalArgRegsSaveSize,
918                               bool ForceMutable = false) const;
919 
920     SDValue LowerCall(TargetLowering::CallLoweringInfo &CLI,
921                       SmallVectorImpl<SDValue> &InVals) const override;
922 
923     /// HandleByVal - Target-specific cleanup for ByVal support.
924     void HandleByVal(CCState *, unsigned &, Align) const override;
925 
926     /// IsEligibleForTailCallOptimization - Check whether the call is eligible
927     /// for tail call optimization. Targets which want to do tail call
928     /// optimization should implement this function.
929     bool IsEligibleForTailCallOptimization(
930         SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
931         bool isCalleeStructRet, bool isCallerStructRet,
932         const SmallVectorImpl<ISD::OutputArg> &Outs,
933         const SmallVectorImpl<SDValue> &OutVals,
934         const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
935         const bool isIndirect) const;
936 
937     bool CanLowerReturn(CallingConv::ID CallConv,
938                         MachineFunction &MF, bool isVarArg,
939                         const SmallVectorImpl<ISD::OutputArg> &Outs,
940                         LLVMContext &Context) const override;
941 
942     SDValue LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
943                         const SmallVectorImpl<ISD::OutputArg> &Outs,
944                         const SmallVectorImpl<SDValue> &OutVals,
945                         const SDLoc &dl, SelectionDAG &DAG) const override;
946 
947     bool isUsedByReturnOnly(SDNode *N, SDValue &Chain) const override;
948 
949     bool mayBeEmittedAsTailCall(const CallInst *CI) const override;
950 
951     bool shouldConsiderGEPOffsetSplit() const override { return true; }
952 
953     bool isUnsupportedFloatingType(EVT VT) const;
954 
955     SDValue getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal, SDValue TrueVal,
956                     SDValue ARMcc, SDValue CCR, SDValue Cmp,
957                     SelectionDAG &DAG) const;
958     SDValue getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
959                       SDValue &ARMcc, SelectionDAG &DAG, const SDLoc &dl) const;
960     SDValue getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
961                       const SDLoc &dl, bool Signaling = false) const;
962     SDValue duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const;
963 
964     SDValue OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const;
965 
966     void SetupEntryBlockForSjLj(MachineInstr &MI, MachineBasicBlock *MBB,
967                                 MachineBasicBlock *DispatchBB, int FI) const;
968 
969     void EmitSjLjDispatchBlock(MachineInstr &MI, MachineBasicBlock *MBB) const;
970 
971     bool RemapAddSubWithFlags(MachineInstr &MI, MachineBasicBlock *BB) const;
972 
973     MachineBasicBlock *EmitStructByval(MachineInstr &MI,
974                                        MachineBasicBlock *MBB) const;
975 
976     MachineBasicBlock *EmitLowered__chkstk(MachineInstr &MI,
977                                            MachineBasicBlock *MBB) const;
978     MachineBasicBlock *EmitLowered__dbzchk(MachineInstr &MI,
979                                            MachineBasicBlock *MBB) const;
980     void addMVEVectorTypes(bool HasMVEFP);
981     void addAllExtLoads(const MVT From, const MVT To, LegalizeAction Action);
982     void setAllExpand(MVT VT);
983   };
984 
985   enum VMOVModImmType {
986     VMOVModImm,
987     VMVNModImm,
988     MVEVMVNModImm,
989     OtherModImm
990   };
991 
992   namespace ARM {
993 
994     FastISel *createFastISel(FunctionLoweringInfo &funcInfo,
995                              const TargetLibraryInfo *libInfo);
996 
997   } // end namespace ARM
998 
999 } // end namespace llvm
1000 
1001 #endif // LLVM_LIB_TARGET_ARM_ARMISELLOWERING_H
1002