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