1 //===- ARMTargetTransformInfo.cpp - ARM specific TTI ----------------------===//
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 #include "ARMTargetTransformInfo.h"
10 #include "ARMSubtarget.h"
11 #include "MCTargetDesc/ARMAddressingModes.h"
12 #include "llvm/ADT/APInt.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/Analysis/LoopInfo.h"
15 #include "llvm/CodeGen/CostTable.h"
16 #include "llvm/CodeGen/ISDOpcodes.h"
17 #include "llvm/CodeGen/ValueTypes.h"
18 #include "llvm/IR/BasicBlock.h"
19 #include "llvm/IR/DataLayout.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/Instruction.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/IntrinsicsARM.h"
25 #include "llvm/IR/PatternMatch.h"
26 #include "llvm/IR/Type.h"
27 #include "llvm/MC/SubtargetFeature.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/KnownBits.h"
30 #include "llvm/Support/MachineValueType.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Transforms/InstCombine/InstCombiner.h"
33 #include "llvm/Transforms/Utils/Local.h"
34 #include "llvm/Transforms/Utils/LoopUtils.h"
35 #include <algorithm>
36 #include <cassert>
37 #include <cstdint>
38 #include <utility>
39 
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "armtti"
43 
44 static cl::opt<bool> EnableMaskedLoadStores(
45   "enable-arm-maskedldst", cl::Hidden, cl::init(true),
46   cl::desc("Enable the generation of masked loads and stores"));
47 
48 static cl::opt<bool> DisableLowOverheadLoops(
49   "disable-arm-loloops", cl::Hidden, cl::init(false),
50   cl::desc("Disable the generation of low-overhead loops"));
51 
52 extern cl::opt<TailPredication::Mode> EnableTailPredication;
53 
54 extern cl::opt<bool> EnableMaskedGatherScatters;
55 
56 extern cl::opt<unsigned> MVEMaxSupportedInterleaveFactor;
57 
58 /// Convert a vector load intrinsic into a simple llvm load instruction.
59 /// This is beneficial when the underlying object being addressed comes
60 /// from a constant, since we get constant-folding for free.
61 static Value *simplifyNeonVld1(const IntrinsicInst &II, unsigned MemAlign,
62                                InstCombiner::BuilderTy &Builder) {
63   auto *IntrAlign = dyn_cast<ConstantInt>(II.getArgOperand(1));
64 
65   if (!IntrAlign)
66     return nullptr;
67 
68   unsigned Alignment = IntrAlign->getLimitedValue() < MemAlign
69                            ? MemAlign
70                            : IntrAlign->getLimitedValue();
71 
72   if (!isPowerOf2_32(Alignment))
73     return nullptr;
74 
75   auto *BCastInst = Builder.CreateBitCast(II.getArgOperand(0),
76                                           PointerType::get(II.getType(), 0));
77   return Builder.CreateAlignedLoad(II.getType(), BCastInst, Align(Alignment));
78 }
79 
80 bool ARMTTIImpl::areInlineCompatible(const Function *Caller,
81                                      const Function *Callee) const {
82   const TargetMachine &TM = getTLI()->getTargetMachine();
83   const FeatureBitset &CallerBits =
84       TM.getSubtargetImpl(*Caller)->getFeatureBits();
85   const FeatureBitset &CalleeBits =
86       TM.getSubtargetImpl(*Callee)->getFeatureBits();
87 
88   // To inline a callee, all features not in the allowed list must match exactly.
89   bool MatchExact = (CallerBits & ~InlineFeaturesAllowed) ==
90                     (CalleeBits & ~InlineFeaturesAllowed);
91   // For features in the allowed list, the callee's features must be a subset of
92   // the callers'.
93   bool MatchSubset = ((CallerBits & CalleeBits) & InlineFeaturesAllowed) ==
94                      (CalleeBits & InlineFeaturesAllowed);
95   return MatchExact && MatchSubset;
96 }
97 
98 bool ARMTTIImpl::shouldFavorBackedgeIndex(const Loop *L) const {
99   if (L->getHeader()->getParent()->hasOptSize())
100     return false;
101   if (ST->hasMVEIntegerOps())
102     return false;
103   return ST->isMClass() && ST->isThumb2() && L->getNumBlocks() == 1;
104 }
105 
106 bool ARMTTIImpl::shouldFavorPostInc() const {
107   if (ST->hasMVEIntegerOps())
108     return true;
109   return false;
110 }
111 
112 Optional<Instruction *>
113 ARMTTIImpl::instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const {
114   using namespace PatternMatch;
115   Intrinsic::ID IID = II.getIntrinsicID();
116   switch (IID) {
117   default:
118     break;
119   case Intrinsic::arm_neon_vld1: {
120     Align MemAlign =
121         getKnownAlignment(II.getArgOperand(0), IC.getDataLayout(), &II,
122                           &IC.getAssumptionCache(), &IC.getDominatorTree());
123     if (Value *V = simplifyNeonVld1(II, MemAlign.value(), IC.Builder)) {
124       return IC.replaceInstUsesWith(II, V);
125     }
126     break;
127   }
128 
129   case Intrinsic::arm_neon_vld2:
130   case Intrinsic::arm_neon_vld3:
131   case Intrinsic::arm_neon_vld4:
132   case Intrinsic::arm_neon_vld2lane:
133   case Intrinsic::arm_neon_vld3lane:
134   case Intrinsic::arm_neon_vld4lane:
135   case Intrinsic::arm_neon_vst1:
136   case Intrinsic::arm_neon_vst2:
137   case Intrinsic::arm_neon_vst3:
138   case Intrinsic::arm_neon_vst4:
139   case Intrinsic::arm_neon_vst2lane:
140   case Intrinsic::arm_neon_vst3lane:
141   case Intrinsic::arm_neon_vst4lane: {
142     Align MemAlign =
143         getKnownAlignment(II.getArgOperand(0), IC.getDataLayout(), &II,
144                           &IC.getAssumptionCache(), &IC.getDominatorTree());
145     unsigned AlignArg = II.getNumArgOperands() - 1;
146     Value *AlignArgOp = II.getArgOperand(AlignArg);
147     MaybeAlign Align = cast<ConstantInt>(AlignArgOp)->getMaybeAlignValue();
148     if (Align && *Align < MemAlign) {
149       return IC.replaceOperand(
150           II, AlignArg,
151           ConstantInt::get(Type::getInt32Ty(II.getContext()), MemAlign.value(),
152                            false));
153     }
154     break;
155   }
156 
157   case Intrinsic::arm_mve_pred_i2v: {
158     Value *Arg = II.getArgOperand(0);
159     Value *ArgArg;
160     if (match(Arg, PatternMatch::m_Intrinsic<Intrinsic::arm_mve_pred_v2i>(
161                        PatternMatch::m_Value(ArgArg))) &&
162         II.getType() == ArgArg->getType()) {
163       return IC.replaceInstUsesWith(II, ArgArg);
164     }
165     Constant *XorMask;
166     if (match(Arg, m_Xor(PatternMatch::m_Intrinsic<Intrinsic::arm_mve_pred_v2i>(
167                              PatternMatch::m_Value(ArgArg)),
168                          PatternMatch::m_Constant(XorMask))) &&
169         II.getType() == ArgArg->getType()) {
170       if (auto *CI = dyn_cast<ConstantInt>(XorMask)) {
171         if (CI->getValue().trunc(16).isAllOnesValue()) {
172           auto TrueVector = IC.Builder.CreateVectorSplat(
173               cast<FixedVectorType>(II.getType())->getNumElements(),
174               IC.Builder.getTrue());
175           return BinaryOperator::Create(Instruction::Xor, ArgArg, TrueVector);
176         }
177       }
178     }
179     KnownBits ScalarKnown(32);
180     if (IC.SimplifyDemandedBits(&II, 0, APInt::getLowBitsSet(32, 16),
181                                 ScalarKnown, 0)) {
182       return &II;
183     }
184     break;
185   }
186   case Intrinsic::arm_mve_pred_v2i: {
187     Value *Arg = II.getArgOperand(0);
188     Value *ArgArg;
189     if (match(Arg, PatternMatch::m_Intrinsic<Intrinsic::arm_mve_pred_i2v>(
190                        PatternMatch::m_Value(ArgArg)))) {
191       return IC.replaceInstUsesWith(II, ArgArg);
192     }
193     if (!II.getMetadata(LLVMContext::MD_range)) {
194       Type *IntTy32 = Type::getInt32Ty(II.getContext());
195       Metadata *M[] = {
196           ConstantAsMetadata::get(ConstantInt::get(IntTy32, 0)),
197           ConstantAsMetadata::get(ConstantInt::get(IntTy32, 0xFFFF))};
198       II.setMetadata(LLVMContext::MD_range, MDNode::get(II.getContext(), M));
199       return &II;
200     }
201     break;
202   }
203   case Intrinsic::arm_mve_vadc:
204   case Intrinsic::arm_mve_vadc_predicated: {
205     unsigned CarryOp =
206         (II.getIntrinsicID() == Intrinsic::arm_mve_vadc_predicated) ? 3 : 2;
207     assert(II.getArgOperand(CarryOp)->getType()->getScalarSizeInBits() == 32 &&
208            "Bad type for intrinsic!");
209 
210     KnownBits CarryKnown(32);
211     if (IC.SimplifyDemandedBits(&II, CarryOp, APInt::getOneBitSet(32, 29),
212                                 CarryKnown)) {
213       return &II;
214     }
215     break;
216   }
217   case Intrinsic::arm_mve_vmldava: {
218     Instruction *I = cast<Instruction>(&II);
219     if (I->hasOneUse()) {
220       auto *User = cast<Instruction>(*I->user_begin());
221       Value *OpZ;
222       if (match(User, m_c_Add(m_Specific(I), m_Value(OpZ))) &&
223           match(I->getOperand(3), m_Zero())) {
224         Value *OpX = I->getOperand(4);
225         Value *OpY = I->getOperand(5);
226         Type *OpTy = OpX->getType();
227 
228         IC.Builder.SetInsertPoint(User);
229         Value *V =
230             IC.Builder.CreateIntrinsic(Intrinsic::arm_mve_vmldava, {OpTy},
231                                        {I->getOperand(0), I->getOperand(1),
232                                         I->getOperand(2), OpZ, OpX, OpY});
233 
234         IC.replaceInstUsesWith(*User, V);
235         return IC.eraseInstFromFunction(*User);
236       }
237     }
238     return None;
239   }
240   }
241   return None;
242 }
243 
244 int ARMTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
245                               TTI::TargetCostKind CostKind) {
246   assert(Ty->isIntegerTy());
247 
248  unsigned Bits = Ty->getPrimitiveSizeInBits();
249  if (Bits == 0 || Imm.getActiveBits() >= 64)
250    return 4;
251 
252   int64_t SImmVal = Imm.getSExtValue();
253   uint64_t ZImmVal = Imm.getZExtValue();
254   if (!ST->isThumb()) {
255     if ((SImmVal >= 0 && SImmVal < 65536) ||
256         (ARM_AM::getSOImmVal(ZImmVal) != -1) ||
257         (ARM_AM::getSOImmVal(~ZImmVal) != -1))
258       return 1;
259     return ST->hasV6T2Ops() ? 2 : 3;
260   }
261   if (ST->isThumb2()) {
262     if ((SImmVal >= 0 && SImmVal < 65536) ||
263         (ARM_AM::getT2SOImmVal(ZImmVal) != -1) ||
264         (ARM_AM::getT2SOImmVal(~ZImmVal) != -1))
265       return 1;
266     return ST->hasV6T2Ops() ? 2 : 3;
267   }
268   // Thumb1, any i8 imm cost 1.
269   if (Bits == 8 || (SImmVal >= 0 && SImmVal < 256))
270     return 1;
271   if ((~SImmVal < 256) || ARM_AM::isThumbImmShiftedVal(ZImmVal))
272     return 2;
273   // Load from constantpool.
274   return 3;
275 }
276 
277 // Constants smaller than 256 fit in the immediate field of
278 // Thumb1 instructions so we return a zero cost and 1 otherwise.
279 int ARMTTIImpl::getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx,
280                                       const APInt &Imm, Type *Ty) {
281   if (Imm.isNonNegative() && Imm.getLimitedValue() < 256)
282     return 0;
283 
284   return 1;
285 }
286 
287 // Checks whether Inst is part of a min(max()) or max(min()) pattern
288 // that will match to an SSAT instruction
289 static bool isSSATMinMaxPattern(Instruction *Inst, const APInt &Imm) {
290   Value *LHS, *RHS;
291   ConstantInt *C;
292   SelectPatternFlavor InstSPF = matchSelectPattern(Inst, LHS, RHS).Flavor;
293 
294   if (InstSPF == SPF_SMAX &&
295       PatternMatch::match(RHS, PatternMatch::m_ConstantInt(C)) &&
296       C->getValue() == Imm && Imm.isNegative() && (-Imm).isPowerOf2()) {
297 
298     auto isSSatMin = [&](Value *MinInst) {
299       if (isa<SelectInst>(MinInst)) {
300         Value *MinLHS, *MinRHS;
301         ConstantInt *MinC;
302         SelectPatternFlavor MinSPF =
303             matchSelectPattern(MinInst, MinLHS, MinRHS).Flavor;
304         if (MinSPF == SPF_SMIN &&
305             PatternMatch::match(MinRHS, PatternMatch::m_ConstantInt(MinC)) &&
306             MinC->getValue() == ((-Imm) - 1))
307           return true;
308       }
309       return false;
310     };
311 
312     if (isSSatMin(Inst->getOperand(1)) ||
313         (Inst->hasNUses(2) && (isSSatMin(*Inst->user_begin()) ||
314                                isSSatMin(*(++Inst->user_begin())))))
315       return true;
316   }
317   return false;
318 }
319 
320 int ARMTTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
321                                   const APInt &Imm, Type *Ty,
322                                   TTI::TargetCostKind CostKind,
323                                   Instruction *Inst) {
324   // Division by a constant can be turned into multiplication, but only if we
325   // know it's constant. So it's not so much that the immediate is cheap (it's
326   // not), but that the alternative is worse.
327   // FIXME: this is probably unneeded with GlobalISel.
328   if ((Opcode == Instruction::SDiv || Opcode == Instruction::UDiv ||
329        Opcode == Instruction::SRem || Opcode == Instruction::URem) &&
330       Idx == 1)
331     return 0;
332 
333   if (Opcode == Instruction::And) {
334     // UXTB/UXTH
335     if (Imm == 255 || Imm == 65535)
336       return 0;
337     // Conversion to BIC is free, and means we can use ~Imm instead.
338     return std::min(getIntImmCost(Imm, Ty, CostKind),
339                     getIntImmCost(~Imm, Ty, CostKind));
340   }
341 
342   if (Opcode == Instruction::Add)
343     // Conversion to SUB is free, and means we can use -Imm instead.
344     return std::min(getIntImmCost(Imm, Ty, CostKind),
345                     getIntImmCost(-Imm, Ty, CostKind));
346 
347   if (Opcode == Instruction::ICmp && Imm.isNegative() &&
348       Ty->getIntegerBitWidth() == 32) {
349     int64_t NegImm = -Imm.getSExtValue();
350     if (ST->isThumb2() && NegImm < 1<<12)
351       // icmp X, #-C -> cmn X, #C
352       return 0;
353     if (ST->isThumb() && NegImm < 1<<8)
354       // icmp X, #-C -> adds X, #C
355       return 0;
356   }
357 
358   // xor a, -1 can always be folded to MVN
359   if (Opcode == Instruction::Xor && Imm.isAllOnesValue())
360     return 0;
361 
362   // Ensures negative constant of min(max()) or max(min()) patterns that
363   // match to SSAT instructions don't get hoisted
364   if (Inst && ((ST->hasV6Ops() && !ST->isThumb()) || ST->isThumb2()) &&
365       Ty->getIntegerBitWidth() <= 32) {
366     if (isSSATMinMaxPattern(Inst, Imm) ||
367         (isa<ICmpInst>(Inst) && Inst->hasOneUse() &&
368          isSSATMinMaxPattern(cast<Instruction>(*Inst->user_begin()), Imm)))
369       return 0;
370   }
371 
372   return getIntImmCost(Imm, Ty, CostKind);
373 }
374 
375 int ARMTTIImpl::getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind) {
376   if (CostKind == TTI::TCK_RecipThroughput &&
377       (ST->hasNEON() || ST->hasMVEIntegerOps())) {
378     // FIXME: The vectorizer is highly sensistive to the cost of these
379     // instructions, which suggests that it may be using the costs incorrectly.
380     // But, for now, just make them free to avoid performance regressions for
381     // vector targets.
382     return 0;
383   }
384   return BaseT::getCFInstrCost(Opcode, CostKind);
385 }
386 
387 int ARMTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
388                                  TTI::CastContextHint CCH,
389                                  TTI::TargetCostKind CostKind,
390                                  const Instruction *I) {
391   int ISD = TLI->InstructionOpcodeToISD(Opcode);
392   assert(ISD && "Invalid opcode");
393 
394   // TODO: Allow non-throughput costs that aren't binary.
395   auto AdjustCost = [&CostKind](int Cost) {
396     if (CostKind != TTI::TCK_RecipThroughput)
397       return Cost == 0 ? 0 : 1;
398     return Cost;
399   };
400   auto IsLegalFPType = [this](EVT VT) {
401     EVT EltVT = VT.getScalarType();
402     return (EltVT == MVT::f32 && ST->hasVFP2Base()) ||
403             (EltVT == MVT::f64 && ST->hasFP64()) ||
404             (EltVT == MVT::f16 && ST->hasFullFP16());
405   };
406 
407   EVT SrcTy = TLI->getValueType(DL, Src);
408   EVT DstTy = TLI->getValueType(DL, Dst);
409 
410   if (!SrcTy.isSimple() || !DstTy.isSimple())
411     return AdjustCost(
412         BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
413 
414   // Extending masked load/Truncating masked stores is expensive because we
415   // currently don't split them. This means that we'll likely end up
416   // loading/storing each element individually (hence the high cost).
417   if ((ST->hasMVEIntegerOps() &&
418        (Opcode == Instruction::Trunc || Opcode == Instruction::ZExt ||
419         Opcode == Instruction::SExt)) ||
420       (ST->hasMVEFloatOps() &&
421        (Opcode == Instruction::FPExt || Opcode == Instruction::FPTrunc) &&
422        IsLegalFPType(SrcTy) && IsLegalFPType(DstTy)))
423     if (CCH == TTI::CastContextHint::Masked && DstTy.getSizeInBits() > 128)
424       return 2 * DstTy.getVectorNumElements() * ST->getMVEVectorCostFactor();
425 
426   // The extend of other kinds of load is free
427   if (CCH == TTI::CastContextHint::Normal ||
428       CCH == TTI::CastContextHint::Masked) {
429     static const TypeConversionCostTblEntry LoadConversionTbl[] = {
430         {ISD::SIGN_EXTEND, MVT::i32, MVT::i16, 0},
431         {ISD::ZERO_EXTEND, MVT::i32, MVT::i16, 0},
432         {ISD::SIGN_EXTEND, MVT::i32, MVT::i8, 0},
433         {ISD::ZERO_EXTEND, MVT::i32, MVT::i8, 0},
434         {ISD::SIGN_EXTEND, MVT::i16, MVT::i8, 0},
435         {ISD::ZERO_EXTEND, MVT::i16, MVT::i8, 0},
436         {ISD::SIGN_EXTEND, MVT::i64, MVT::i32, 1},
437         {ISD::ZERO_EXTEND, MVT::i64, MVT::i32, 1},
438         {ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 1},
439         {ISD::ZERO_EXTEND, MVT::i64, MVT::i16, 1},
440         {ISD::SIGN_EXTEND, MVT::i64, MVT::i8, 1},
441         {ISD::ZERO_EXTEND, MVT::i64, MVT::i8, 1},
442     };
443     if (const auto *Entry = ConvertCostTableLookup(
444             LoadConversionTbl, ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
445       return AdjustCost(Entry->Cost);
446 
447     static const TypeConversionCostTblEntry MVELoadConversionTbl[] = {
448         {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 0},
449         {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 0},
450         {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 0},
451         {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 0},
452         {ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 0},
453         {ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 0},
454         // The following extend from a legal type to an illegal type, so need to
455         // split the load. This introduced an extra load operation, but the
456         // extend is still "free".
457         {ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 1},
458         {ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 1},
459         {ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 3},
460         {ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 3},
461         {ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 1},
462         {ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 1},
463     };
464     if (SrcTy.isVector() && ST->hasMVEIntegerOps()) {
465       if (const auto *Entry =
466               ConvertCostTableLookup(MVELoadConversionTbl, ISD,
467                                      DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
468         return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor());
469     }
470 
471     static const TypeConversionCostTblEntry MVEFLoadConversionTbl[] = {
472         // FPExtends are similar but also require the VCVT instructions.
473         {ISD::FP_EXTEND, MVT::v4f32, MVT::v4f16, 1},
474         {ISD::FP_EXTEND, MVT::v8f32, MVT::v8f16, 3},
475     };
476     if (SrcTy.isVector() && ST->hasMVEFloatOps()) {
477       if (const auto *Entry =
478               ConvertCostTableLookup(MVEFLoadConversionTbl, ISD,
479                                      DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
480         return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor());
481     }
482 
483     // The truncate of a store is free. This is the mirror of extends above.
484     static const TypeConversionCostTblEntry MVEStoreConversionTbl[] = {
485         {ISD::TRUNCATE, MVT::v4i32, MVT::v4i16, 0},
486         {ISD::TRUNCATE, MVT::v4i32, MVT::v4i8, 0},
487         {ISD::TRUNCATE, MVT::v8i16, MVT::v8i8, 0},
488         {ISD::TRUNCATE, MVT::v8i32, MVT::v8i16, 1},
489         {ISD::TRUNCATE, MVT::v16i32, MVT::v16i8, 3},
490         {ISD::TRUNCATE, MVT::v16i16, MVT::v16i8, 1},
491     };
492     if (SrcTy.isVector() && ST->hasMVEIntegerOps()) {
493       if (const auto *Entry =
494               ConvertCostTableLookup(MVEStoreConversionTbl, ISD,
495                                      SrcTy.getSimpleVT(), DstTy.getSimpleVT()))
496         return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor());
497     }
498 
499     static const TypeConversionCostTblEntry MVEFStoreConversionTbl[] = {
500         {ISD::FP_ROUND, MVT::v4f32, MVT::v4f16, 1},
501         {ISD::FP_ROUND, MVT::v8f32, MVT::v8f16, 3},
502     };
503     if (SrcTy.isVector() && ST->hasMVEFloatOps()) {
504       if (const auto *Entry =
505               ConvertCostTableLookup(MVEFStoreConversionTbl, ISD,
506                                      SrcTy.getSimpleVT(), DstTy.getSimpleVT()))
507         return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor());
508     }
509   }
510 
511   // NEON vector operations that can extend their inputs.
512   if ((ISD == ISD::SIGN_EXTEND || ISD == ISD::ZERO_EXTEND) &&
513       I && I->hasOneUse() && ST->hasNEON() && SrcTy.isVector()) {
514     static const TypeConversionCostTblEntry NEONDoubleWidthTbl[] = {
515       // vaddl
516       { ISD::ADD, MVT::v4i32, MVT::v4i16, 0 },
517       { ISD::ADD, MVT::v8i16, MVT::v8i8,  0 },
518       // vsubl
519       { ISD::SUB, MVT::v4i32, MVT::v4i16, 0 },
520       { ISD::SUB, MVT::v8i16, MVT::v8i8,  0 },
521       // vmull
522       { ISD::MUL, MVT::v4i32, MVT::v4i16, 0 },
523       { ISD::MUL, MVT::v8i16, MVT::v8i8,  0 },
524       // vshll
525       { ISD::SHL, MVT::v4i32, MVT::v4i16, 0 },
526       { ISD::SHL, MVT::v8i16, MVT::v8i8,  0 },
527     };
528 
529     auto *User = cast<Instruction>(*I->user_begin());
530     int UserISD = TLI->InstructionOpcodeToISD(User->getOpcode());
531     if (auto *Entry = ConvertCostTableLookup(NEONDoubleWidthTbl, UserISD,
532                                              DstTy.getSimpleVT(),
533                                              SrcTy.getSimpleVT())) {
534       return AdjustCost(Entry->Cost);
535     }
536   }
537 
538   // Single to/from double precision conversions.
539   if (Src->isVectorTy() && ST->hasNEON() &&
540       ((ISD == ISD::FP_ROUND && SrcTy.getScalarType() == MVT::f64 &&
541         DstTy.getScalarType() == MVT::f32) ||
542        (ISD == ISD::FP_EXTEND && SrcTy.getScalarType() == MVT::f32 &&
543         DstTy.getScalarType() == MVT::f64))) {
544     static const CostTblEntry NEONFltDblTbl[] = {
545         // Vector fptrunc/fpext conversions.
546         {ISD::FP_ROUND, MVT::v2f64, 2},
547         {ISD::FP_EXTEND, MVT::v2f32, 2},
548         {ISD::FP_EXTEND, MVT::v4f32, 4}};
549 
550     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
551     if (const auto *Entry = CostTableLookup(NEONFltDblTbl, ISD, LT.second))
552       return AdjustCost(LT.first * Entry->Cost);
553   }
554 
555   // Some arithmetic, load and store operations have specific instructions
556   // to cast up/down their types automatically at no extra cost.
557   // TODO: Get these tables to know at least what the related operations are.
558   static const TypeConversionCostTblEntry NEONVectorConversionTbl[] = {
559     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
560     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
561     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 1 },
562     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 1 },
563     { ISD::TRUNCATE,    MVT::v4i32, MVT::v4i64, 0 },
564     { ISD::TRUNCATE,    MVT::v4i16, MVT::v4i32, 1 },
565 
566     // The number of vmovl instructions for the extension.
567     { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8,  1 },
568     { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8,  1 },
569     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8,  2 },
570     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8,  2 },
571     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i8,  3 },
572     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i8,  3 },
573     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i16, 2 },
574     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i16, 2 },
575     { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
576     { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
577     { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
578     { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
579     { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
580     { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
581     { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
582     { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
583     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
584     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
585 
586     // Operations that we legalize using splitting.
587     { ISD::TRUNCATE,    MVT::v16i8, MVT::v16i32, 6 },
588     { ISD::TRUNCATE,    MVT::v8i8, MVT::v8i32, 3 },
589 
590     // Vector float <-> i32 conversions.
591     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i32, 1 },
592     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i32, 1 },
593 
594     { ISD::SINT_TO_FP,  MVT::v2f32, MVT::v2i8, 3 },
595     { ISD::UINT_TO_FP,  MVT::v2f32, MVT::v2i8, 3 },
596     { ISD::SINT_TO_FP,  MVT::v2f32, MVT::v2i16, 2 },
597     { ISD::UINT_TO_FP,  MVT::v2f32, MVT::v2i16, 2 },
598     { ISD::SINT_TO_FP,  MVT::v2f32, MVT::v2i32, 1 },
599     { ISD::UINT_TO_FP,  MVT::v2f32, MVT::v2i32, 1 },
600     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i1, 3 },
601     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i1, 3 },
602     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i8, 3 },
603     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i8, 3 },
604     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i16, 2 },
605     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i16, 2 },
606     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i16, 4 },
607     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i16, 4 },
608     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i32, 2 },
609     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i32, 2 },
610     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i16, 8 },
611     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i16, 8 },
612     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i32, 4 },
613     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i32, 4 },
614 
615     { ISD::FP_TO_SINT,  MVT::v4i32, MVT::v4f32, 1 },
616     { ISD::FP_TO_UINT,  MVT::v4i32, MVT::v4f32, 1 },
617     { ISD::FP_TO_SINT,  MVT::v4i8, MVT::v4f32, 3 },
618     { ISD::FP_TO_UINT,  MVT::v4i8, MVT::v4f32, 3 },
619     { ISD::FP_TO_SINT,  MVT::v4i16, MVT::v4f32, 2 },
620     { ISD::FP_TO_UINT,  MVT::v4i16, MVT::v4f32, 2 },
621 
622     // Vector double <-> i32 conversions.
623     { ISD::SINT_TO_FP,  MVT::v2f64, MVT::v2i32, 2 },
624     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i32, 2 },
625 
626     { ISD::SINT_TO_FP,  MVT::v2f64, MVT::v2i8, 4 },
627     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i8, 4 },
628     { ISD::SINT_TO_FP,  MVT::v2f64, MVT::v2i16, 3 },
629     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i16, 3 },
630     { ISD::SINT_TO_FP,  MVT::v2f64, MVT::v2i32, 2 },
631     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i32, 2 },
632 
633     { ISD::FP_TO_SINT,  MVT::v2i32, MVT::v2f64, 2 },
634     { ISD::FP_TO_UINT,  MVT::v2i32, MVT::v2f64, 2 },
635     { ISD::FP_TO_SINT,  MVT::v8i16, MVT::v8f32, 4 },
636     { ISD::FP_TO_UINT,  MVT::v8i16, MVT::v8f32, 4 },
637     { ISD::FP_TO_SINT,  MVT::v16i16, MVT::v16f32, 8 },
638     { ISD::FP_TO_UINT,  MVT::v16i16, MVT::v16f32, 8 }
639   };
640 
641   if (SrcTy.isVector() && ST->hasNEON()) {
642     if (const auto *Entry = ConvertCostTableLookup(NEONVectorConversionTbl, ISD,
643                                                    DstTy.getSimpleVT(),
644                                                    SrcTy.getSimpleVT()))
645       return AdjustCost(Entry->Cost);
646   }
647 
648   // Scalar float to integer conversions.
649   static const TypeConversionCostTblEntry NEONFloatConversionTbl[] = {
650     { ISD::FP_TO_SINT,  MVT::i1, MVT::f32, 2 },
651     { ISD::FP_TO_UINT,  MVT::i1, MVT::f32, 2 },
652     { ISD::FP_TO_SINT,  MVT::i1, MVT::f64, 2 },
653     { ISD::FP_TO_UINT,  MVT::i1, MVT::f64, 2 },
654     { ISD::FP_TO_SINT,  MVT::i8, MVT::f32, 2 },
655     { ISD::FP_TO_UINT,  MVT::i8, MVT::f32, 2 },
656     { ISD::FP_TO_SINT,  MVT::i8, MVT::f64, 2 },
657     { ISD::FP_TO_UINT,  MVT::i8, MVT::f64, 2 },
658     { ISD::FP_TO_SINT,  MVT::i16, MVT::f32, 2 },
659     { ISD::FP_TO_UINT,  MVT::i16, MVT::f32, 2 },
660     { ISD::FP_TO_SINT,  MVT::i16, MVT::f64, 2 },
661     { ISD::FP_TO_UINT,  MVT::i16, MVT::f64, 2 },
662     { ISD::FP_TO_SINT,  MVT::i32, MVT::f32, 2 },
663     { ISD::FP_TO_UINT,  MVT::i32, MVT::f32, 2 },
664     { ISD::FP_TO_SINT,  MVT::i32, MVT::f64, 2 },
665     { ISD::FP_TO_UINT,  MVT::i32, MVT::f64, 2 },
666     { ISD::FP_TO_SINT,  MVT::i64, MVT::f32, 10 },
667     { ISD::FP_TO_UINT,  MVT::i64, MVT::f32, 10 },
668     { ISD::FP_TO_SINT,  MVT::i64, MVT::f64, 10 },
669     { ISD::FP_TO_UINT,  MVT::i64, MVT::f64, 10 }
670   };
671   if (SrcTy.isFloatingPoint() && ST->hasNEON()) {
672     if (const auto *Entry = ConvertCostTableLookup(NEONFloatConversionTbl, ISD,
673                                                    DstTy.getSimpleVT(),
674                                                    SrcTy.getSimpleVT()))
675       return AdjustCost(Entry->Cost);
676   }
677 
678   // Scalar integer to float conversions.
679   static const TypeConversionCostTblEntry NEONIntegerConversionTbl[] = {
680     { ISD::SINT_TO_FP,  MVT::f32, MVT::i1, 2 },
681     { ISD::UINT_TO_FP,  MVT::f32, MVT::i1, 2 },
682     { ISD::SINT_TO_FP,  MVT::f64, MVT::i1, 2 },
683     { ISD::UINT_TO_FP,  MVT::f64, MVT::i1, 2 },
684     { ISD::SINT_TO_FP,  MVT::f32, MVT::i8, 2 },
685     { ISD::UINT_TO_FP,  MVT::f32, MVT::i8, 2 },
686     { ISD::SINT_TO_FP,  MVT::f64, MVT::i8, 2 },
687     { ISD::UINT_TO_FP,  MVT::f64, MVT::i8, 2 },
688     { ISD::SINT_TO_FP,  MVT::f32, MVT::i16, 2 },
689     { ISD::UINT_TO_FP,  MVT::f32, MVT::i16, 2 },
690     { ISD::SINT_TO_FP,  MVT::f64, MVT::i16, 2 },
691     { ISD::UINT_TO_FP,  MVT::f64, MVT::i16, 2 },
692     { ISD::SINT_TO_FP,  MVT::f32, MVT::i32, 2 },
693     { ISD::UINT_TO_FP,  MVT::f32, MVT::i32, 2 },
694     { ISD::SINT_TO_FP,  MVT::f64, MVT::i32, 2 },
695     { ISD::UINT_TO_FP,  MVT::f64, MVT::i32, 2 },
696     { ISD::SINT_TO_FP,  MVT::f32, MVT::i64, 10 },
697     { ISD::UINT_TO_FP,  MVT::f32, MVT::i64, 10 },
698     { ISD::SINT_TO_FP,  MVT::f64, MVT::i64, 10 },
699     { ISD::UINT_TO_FP,  MVT::f64, MVT::i64, 10 }
700   };
701 
702   if (SrcTy.isInteger() && ST->hasNEON()) {
703     if (const auto *Entry = ConvertCostTableLookup(NEONIntegerConversionTbl,
704                                                    ISD, DstTy.getSimpleVT(),
705                                                    SrcTy.getSimpleVT()))
706       return AdjustCost(Entry->Cost);
707   }
708 
709   // MVE extend costs, taken from codegen tests. i8->i16 or i16->i32 is one
710   // instruction, i8->i32 is two. i64 zexts are an VAND with a constant, sext
711   // are linearised so take more.
712   static const TypeConversionCostTblEntry MVEVectorConversionTbl[] = {
713     { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
714     { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
715     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
716     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
717     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i8, 10 },
718     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i8, 2 },
719     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
720     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
721     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i16, 10 },
722     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i16, 2 },
723     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 8 },
724     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 2 },
725   };
726 
727   if (SrcTy.isVector() && ST->hasMVEIntegerOps()) {
728     if (const auto *Entry = ConvertCostTableLookup(MVEVectorConversionTbl,
729                                                    ISD, DstTy.getSimpleVT(),
730                                                    SrcTy.getSimpleVT()))
731       return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor());
732   }
733 
734   if (ISD == ISD::FP_ROUND || ISD == ISD::FP_EXTEND) {
735     // As general rule, fp converts that were not matched above are scalarized
736     // and cost 1 vcvt for each lane, so long as the instruction is available.
737     // If not it will become a series of function calls.
738     const int CallCost = getCallInstrCost(nullptr, Dst, {Src}, CostKind);
739     int Lanes = 1;
740     if (SrcTy.isFixedLengthVector())
741       Lanes = SrcTy.getVectorNumElements();
742 
743     if (IsLegalFPType(SrcTy) && IsLegalFPType(DstTy))
744       return Lanes;
745     else
746       return Lanes * CallCost;
747   }
748 
749   // Scalar integer conversion costs.
750   static const TypeConversionCostTblEntry ARMIntegerConversionTbl[] = {
751     // i16 -> i64 requires two dependent operations.
752     { ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 2 },
753 
754     // Truncates on i64 are assumed to be free.
755     { ISD::TRUNCATE,    MVT::i32, MVT::i64, 0 },
756     { ISD::TRUNCATE,    MVT::i16, MVT::i64, 0 },
757     { ISD::TRUNCATE,    MVT::i8,  MVT::i64, 0 },
758     { ISD::TRUNCATE,    MVT::i1,  MVT::i64, 0 }
759   };
760 
761   if (SrcTy.isInteger()) {
762     if (const auto *Entry = ConvertCostTableLookup(ARMIntegerConversionTbl, ISD,
763                                                    DstTy.getSimpleVT(),
764                                                    SrcTy.getSimpleVT()))
765       return AdjustCost(Entry->Cost);
766   }
767 
768   int BaseCost = ST->hasMVEIntegerOps() && Src->isVectorTy()
769                      ? ST->getMVEVectorCostFactor()
770                      : 1;
771   return AdjustCost(
772       BaseCost * BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
773 }
774 
775 int ARMTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy,
776                                    unsigned Index) {
777   // Penalize inserting into an D-subregister. We end up with a three times
778   // lower estimated throughput on swift.
779   if (ST->hasSlowLoadDSubregister() && Opcode == Instruction::InsertElement &&
780       ValTy->isVectorTy() && ValTy->getScalarSizeInBits() <= 32)
781     return 3;
782 
783   if (ST->hasNEON() && (Opcode == Instruction::InsertElement ||
784                         Opcode == Instruction::ExtractElement)) {
785     // Cross-class copies are expensive on many microarchitectures,
786     // so assume they are expensive by default.
787     if (cast<VectorType>(ValTy)->getElementType()->isIntegerTy())
788       return 3;
789 
790     // Even if it's not a cross class copy, this likely leads to mixing
791     // of NEON and VFP code and should be therefore penalized.
792     if (ValTy->isVectorTy() &&
793         ValTy->getScalarSizeInBits() <= 32)
794       return std::max(BaseT::getVectorInstrCost(Opcode, ValTy, Index), 2U);
795   }
796 
797   if (ST->hasMVEIntegerOps() && (Opcode == Instruction::InsertElement ||
798                                  Opcode == Instruction::ExtractElement)) {
799     // We say MVE moves costs at least the MVEVectorCostFactor, even though
800     // they are scalar instructions. This helps prevent mixing scalar and
801     // vector, to prevent vectorising where we end up just scalarising the
802     // result anyway.
803     return std::max(BaseT::getVectorInstrCost(Opcode, ValTy, Index),
804                     ST->getMVEVectorCostFactor()) *
805            cast<FixedVectorType>(ValTy)->getNumElements() / 2;
806   }
807 
808   return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
809 }
810 
811 int ARMTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
812                                    TTI::TargetCostKind CostKind,
813                                    const Instruction *I) {
814   int ISD = TLI->InstructionOpcodeToISD(Opcode);
815 
816   // Thumb scalar code size cost for select.
817   if (CostKind == TTI::TCK_CodeSize && ISD == ISD::SELECT &&
818       ST->isThumb() && !ValTy->isVectorTy()) {
819     // Assume expensive structs.
820     if (TLI->getValueType(DL, ValTy, true) == MVT::Other)
821       return TTI::TCC_Expensive;
822 
823     // Select costs can vary because they:
824     // - may require one or more conditional mov (including an IT),
825     // - can't operate directly on immediates,
826     // - require live flags, which we can't copy around easily.
827     int Cost = TLI->getTypeLegalizationCost(DL, ValTy).first;
828 
829     // Possible IT instruction for Thumb2, or more for Thumb1.
830     ++Cost;
831 
832     // i1 values may need rematerialising by using mov immediates and/or
833     // flag setting instructions.
834     if (ValTy->isIntegerTy(1))
835       ++Cost;
836 
837     return Cost;
838   }
839 
840   if (CostKind != TTI::TCK_RecipThroughput)
841     return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, CostKind, I);
842 
843   // On NEON a vector select gets lowered to vbsl.
844   if (ST->hasNEON() && ValTy->isVectorTy() && ISD == ISD::SELECT) {
845     // Lowering of some vector selects is currently far from perfect.
846     static const TypeConversionCostTblEntry NEONVectorSelectTbl[] = {
847       { ISD::SELECT, MVT::v4i1, MVT::v4i64, 4*4 + 1*2 + 1 },
848       { ISD::SELECT, MVT::v8i1, MVT::v8i64, 50 },
849       { ISD::SELECT, MVT::v16i1, MVT::v16i64, 100 }
850     };
851 
852     EVT SelCondTy = TLI->getValueType(DL, CondTy);
853     EVT SelValTy = TLI->getValueType(DL, ValTy);
854     if (SelCondTy.isSimple() && SelValTy.isSimple()) {
855       if (const auto *Entry = ConvertCostTableLookup(NEONVectorSelectTbl, ISD,
856                                                      SelCondTy.getSimpleVT(),
857                                                      SelValTy.getSimpleVT()))
858         return Entry->Cost;
859     }
860 
861     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
862     return LT.first;
863   }
864 
865   int BaseCost = ST->hasMVEIntegerOps() && ValTy->isVectorTy()
866                      ? ST->getMVEVectorCostFactor()
867                      : 1;
868   return BaseCost * BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, CostKind,
869                                               I);
870 }
871 
872 int ARMTTIImpl::getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
873                                           const SCEV *Ptr) {
874   // Address computations in vectorized code with non-consecutive addresses will
875   // likely result in more instructions compared to scalar code where the
876   // computation can more often be merged into the index mode. The resulting
877   // extra micro-ops can significantly decrease throughput.
878   unsigned NumVectorInstToHideOverhead = 10;
879   int MaxMergeDistance = 64;
880 
881   if (ST->hasNEON()) {
882     if (Ty->isVectorTy() && SE &&
883         !BaseT::isConstantStridedAccessLessThan(SE, Ptr, MaxMergeDistance + 1))
884       return NumVectorInstToHideOverhead;
885 
886     // In many cases the address computation is not merged into the instruction
887     // addressing mode.
888     return 1;
889   }
890   return BaseT::getAddressComputationCost(Ty, SE, Ptr);
891 }
892 
893 bool ARMTTIImpl::isProfitableLSRChainElement(Instruction *I) {
894   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
895     // If a VCTP is part of a chain, it's already profitable and shouldn't be
896     // optimized, else LSR may block tail-predication.
897     switch (II->getIntrinsicID()) {
898     case Intrinsic::arm_mve_vctp8:
899     case Intrinsic::arm_mve_vctp16:
900     case Intrinsic::arm_mve_vctp32:
901     case Intrinsic::arm_mve_vctp64:
902       return true;
903     default:
904       break;
905     }
906   }
907   return false;
908 }
909 
910 bool ARMTTIImpl::isLegalMaskedLoad(Type *DataTy, Align Alignment) {
911   if (!EnableMaskedLoadStores || !ST->hasMVEIntegerOps())
912     return false;
913 
914   if (auto *VecTy = dyn_cast<FixedVectorType>(DataTy)) {
915     // Don't support v2i1 yet.
916     if (VecTy->getNumElements() == 2)
917       return false;
918 
919     // We don't support extending fp types.
920      unsigned VecWidth = DataTy->getPrimitiveSizeInBits();
921     if (VecWidth != 128 && VecTy->getElementType()->isFloatingPointTy())
922       return false;
923   }
924 
925   unsigned EltWidth = DataTy->getScalarSizeInBits();
926   return (EltWidth == 32 && Alignment >= 4) ||
927          (EltWidth == 16 && Alignment >= 2) || (EltWidth == 8);
928 }
929 
930 bool ARMTTIImpl::isLegalMaskedGather(Type *Ty, Align Alignment) {
931   if (!EnableMaskedGatherScatters || !ST->hasMVEIntegerOps())
932     return false;
933 
934   // This method is called in 2 places:
935   //  - from the vectorizer with a scalar type, in which case we need to get
936   //  this as good as we can with the limited info we have (and rely on the cost
937   //  model for the rest).
938   //  - from the masked intrinsic lowering pass with the actual vector type.
939   // For MVE, we have a custom lowering pass that will already have custom
940   // legalised any gathers that we can to MVE intrinsics, and want to expand all
941   // the rest. The pass runs before the masked intrinsic lowering pass, so if we
942   // are here, we know we want to expand.
943   if (isa<VectorType>(Ty))
944     return false;
945 
946   unsigned EltWidth = Ty->getScalarSizeInBits();
947   return ((EltWidth == 32 && Alignment >= 4) ||
948           (EltWidth == 16 && Alignment >= 2) || EltWidth == 8);
949 }
950 
951 int ARMTTIImpl::getMemcpyCost(const Instruction *I) {
952   const MemCpyInst *MI = dyn_cast<MemCpyInst>(I);
953   assert(MI && "MemcpyInst expected");
954   ConstantInt *C = dyn_cast<ConstantInt>(MI->getLength());
955 
956   // To model the cost of a library call, we assume 1 for the call, and
957   // 3 for the argument setup.
958   const unsigned LibCallCost = 4;
959 
960   // If 'size' is not a constant, a library call will be generated.
961   if (!C)
962     return LibCallCost;
963 
964   const unsigned Size = C->getValue().getZExtValue();
965   const Align DstAlign = *MI->getDestAlign();
966   const Align SrcAlign = *MI->getSourceAlign();
967   const Function *F = I->getParent()->getParent();
968   const unsigned Limit = TLI->getMaxStoresPerMemmove(F->hasMinSize());
969   std::vector<EVT> MemOps;
970 
971   // MemOps will be poplulated with a list of data types that needs to be
972   // loaded and stored. That's why we multiply the number of elements by 2 to
973   // get the cost for this memcpy.
974   if (getTLI()->findOptimalMemOpLowering(
975           MemOps, Limit,
976           MemOp::Copy(Size, /*DstAlignCanChange*/ false, DstAlign, SrcAlign,
977                       /*IsVolatile*/ true),
978           MI->getDestAddressSpace(), MI->getSourceAddressSpace(),
979           F->getAttributes()))
980     return MemOps.size() * 2;
981 
982   // If we can't find an optimal memop lowering, return the default cost
983   return LibCallCost;
984 }
985 
986 int ARMTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *Tp,
987                                int Index, VectorType *SubTp) {
988   if (ST->hasNEON()) {
989     if (Kind == TTI::SK_Broadcast) {
990       static const CostTblEntry NEONDupTbl[] = {
991           // VDUP handles these cases.
992           {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
993           {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
994           {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
995           {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
996           {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1},
997           {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1},
998 
999           {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
1000           {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
1001           {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
1002           {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1}};
1003 
1004       std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
1005 
1006       if (const auto *Entry =
1007               CostTableLookup(NEONDupTbl, ISD::VECTOR_SHUFFLE, LT.second))
1008         return LT.first * Entry->Cost;
1009     }
1010     if (Kind == TTI::SK_Reverse) {
1011       static const CostTblEntry NEONShuffleTbl[] = {
1012           // Reverse shuffle cost one instruction if we are shuffling within a
1013           // double word (vrev) or two if we shuffle a quad word (vrev, vext).
1014           {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
1015           {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
1016           {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
1017           {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
1018           {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1},
1019           {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1},
1020 
1021           {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
1022           {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
1023           {ISD::VECTOR_SHUFFLE, MVT::v8i16, 2},
1024           {ISD::VECTOR_SHUFFLE, MVT::v16i8, 2}};
1025 
1026       std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
1027 
1028       if (const auto *Entry =
1029               CostTableLookup(NEONShuffleTbl, ISD::VECTOR_SHUFFLE, LT.second))
1030         return LT.first * Entry->Cost;
1031     }
1032     if (Kind == TTI::SK_Select) {
1033       static const CostTblEntry NEONSelShuffleTbl[] = {
1034           // Select shuffle cost table for ARM. Cost is the number of
1035           // instructions
1036           // required to create the shuffled vector.
1037 
1038           {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
1039           {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
1040           {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
1041           {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
1042 
1043           {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
1044           {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
1045           {ISD::VECTOR_SHUFFLE, MVT::v4i16, 2},
1046 
1047           {ISD::VECTOR_SHUFFLE, MVT::v8i16, 16},
1048 
1049           {ISD::VECTOR_SHUFFLE, MVT::v16i8, 32}};
1050 
1051       std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
1052       if (const auto *Entry = CostTableLookup(NEONSelShuffleTbl,
1053                                               ISD::VECTOR_SHUFFLE, LT.second))
1054         return LT.first * Entry->Cost;
1055     }
1056   }
1057   if (ST->hasMVEIntegerOps()) {
1058     if (Kind == TTI::SK_Broadcast) {
1059       static const CostTblEntry MVEDupTbl[] = {
1060           // VDUP handles these cases.
1061           {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
1062           {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
1063           {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1},
1064           {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
1065           {ISD::VECTOR_SHUFFLE, MVT::v8f16, 1}};
1066 
1067       std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
1068 
1069       if (const auto *Entry = CostTableLookup(MVEDupTbl, ISD::VECTOR_SHUFFLE,
1070                                               LT.second))
1071         return LT.first * Entry->Cost * ST->getMVEVectorCostFactor();
1072     }
1073   }
1074   int BaseCost = ST->hasMVEIntegerOps() && Tp->isVectorTy()
1075                      ? ST->getMVEVectorCostFactor()
1076                      : 1;
1077   return BaseCost * BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
1078 }
1079 
1080 int ARMTTIImpl::getArithmeticInstrCost(unsigned Opcode, Type *Ty,
1081                                        TTI::TargetCostKind CostKind,
1082                                        TTI::OperandValueKind Op1Info,
1083                                        TTI::OperandValueKind Op2Info,
1084                                        TTI::OperandValueProperties Opd1PropInfo,
1085                                        TTI::OperandValueProperties Opd2PropInfo,
1086                                        ArrayRef<const Value *> Args,
1087                                        const Instruction *CxtI) {
1088   int ISDOpcode = TLI->InstructionOpcodeToISD(Opcode);
1089   if (ST->isThumb() && CostKind == TTI::TCK_CodeSize && Ty->isIntegerTy(1)) {
1090     // Make operations on i1 relatively expensive as this often involves
1091     // combining predicates. AND and XOR should be easier to handle with IT
1092     // blocks.
1093     switch (ISDOpcode) {
1094     default:
1095       break;
1096     case ISD::AND:
1097     case ISD::XOR:
1098       return 2;
1099     case ISD::OR:
1100       return 3;
1101     }
1102   }
1103 
1104   // TODO: Handle more cost kinds.
1105   if (CostKind != TTI::TCK_RecipThroughput)
1106     return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
1107                                          Op2Info, Opd1PropInfo,
1108                                          Opd2PropInfo, Args, CxtI);
1109 
1110   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
1111 
1112   if (ST->hasNEON()) {
1113     const unsigned FunctionCallDivCost = 20;
1114     const unsigned ReciprocalDivCost = 10;
1115     static const CostTblEntry CostTbl[] = {
1116       // Division.
1117       // These costs are somewhat random. Choose a cost of 20 to indicate that
1118       // vectorizing devision (added function call) is going to be very expensive.
1119       // Double registers types.
1120       { ISD::SDIV, MVT::v1i64, 1 * FunctionCallDivCost},
1121       { ISD::UDIV, MVT::v1i64, 1 * FunctionCallDivCost},
1122       { ISD::SREM, MVT::v1i64, 1 * FunctionCallDivCost},
1123       { ISD::UREM, MVT::v1i64, 1 * FunctionCallDivCost},
1124       { ISD::SDIV, MVT::v2i32, 2 * FunctionCallDivCost},
1125       { ISD::UDIV, MVT::v2i32, 2 * FunctionCallDivCost},
1126       { ISD::SREM, MVT::v2i32, 2 * FunctionCallDivCost},
1127       { ISD::UREM, MVT::v2i32, 2 * FunctionCallDivCost},
1128       { ISD::SDIV, MVT::v4i16,     ReciprocalDivCost},
1129       { ISD::UDIV, MVT::v4i16,     ReciprocalDivCost},
1130       { ISD::SREM, MVT::v4i16, 4 * FunctionCallDivCost},
1131       { ISD::UREM, MVT::v4i16, 4 * FunctionCallDivCost},
1132       { ISD::SDIV, MVT::v8i8,      ReciprocalDivCost},
1133       { ISD::UDIV, MVT::v8i8,      ReciprocalDivCost},
1134       { ISD::SREM, MVT::v8i8,  8 * FunctionCallDivCost},
1135       { ISD::UREM, MVT::v8i8,  8 * FunctionCallDivCost},
1136       // Quad register types.
1137       { ISD::SDIV, MVT::v2i64, 2 * FunctionCallDivCost},
1138       { ISD::UDIV, MVT::v2i64, 2 * FunctionCallDivCost},
1139       { ISD::SREM, MVT::v2i64, 2 * FunctionCallDivCost},
1140       { ISD::UREM, MVT::v2i64, 2 * FunctionCallDivCost},
1141       { ISD::SDIV, MVT::v4i32, 4 * FunctionCallDivCost},
1142       { ISD::UDIV, MVT::v4i32, 4 * FunctionCallDivCost},
1143       { ISD::SREM, MVT::v4i32, 4 * FunctionCallDivCost},
1144       { ISD::UREM, MVT::v4i32, 4 * FunctionCallDivCost},
1145       { ISD::SDIV, MVT::v8i16, 8 * FunctionCallDivCost},
1146       { ISD::UDIV, MVT::v8i16, 8 * FunctionCallDivCost},
1147       { ISD::SREM, MVT::v8i16, 8 * FunctionCallDivCost},
1148       { ISD::UREM, MVT::v8i16, 8 * FunctionCallDivCost},
1149       { ISD::SDIV, MVT::v16i8, 16 * FunctionCallDivCost},
1150       { ISD::UDIV, MVT::v16i8, 16 * FunctionCallDivCost},
1151       { ISD::SREM, MVT::v16i8, 16 * FunctionCallDivCost},
1152       { ISD::UREM, MVT::v16i8, 16 * FunctionCallDivCost},
1153       // Multiplication.
1154     };
1155 
1156     if (const auto *Entry = CostTableLookup(CostTbl, ISDOpcode, LT.second))
1157       return LT.first * Entry->Cost;
1158 
1159     int Cost = BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
1160                                              Op2Info,
1161                                              Opd1PropInfo, Opd2PropInfo);
1162 
1163     // This is somewhat of a hack. The problem that we are facing is that SROA
1164     // creates a sequence of shift, and, or instructions to construct values.
1165     // These sequences are recognized by the ISel and have zero-cost. Not so for
1166     // the vectorized code. Because we have support for v2i64 but not i64 those
1167     // sequences look particularly beneficial to vectorize.
1168     // To work around this we increase the cost of v2i64 operations to make them
1169     // seem less beneficial.
1170     if (LT.second == MVT::v2i64 &&
1171         Op2Info == TargetTransformInfo::OK_UniformConstantValue)
1172       Cost += 4;
1173 
1174     return Cost;
1175   }
1176 
1177   // If this operation is a shift on arm/thumb2, it might well be folded into
1178   // the following instruction, hence having a cost of 0.
1179   auto LooksLikeAFreeShift = [&]() {
1180     if (ST->isThumb1Only() || Ty->isVectorTy())
1181       return false;
1182 
1183     if (!CxtI || !CxtI->hasOneUse() || !CxtI->isShift())
1184       return false;
1185     if (Op2Info != TargetTransformInfo::OK_UniformConstantValue)
1186       return false;
1187 
1188     // Folded into a ADC/ADD/AND/BIC/CMP/EOR/MVN/ORR/ORN/RSB/SBC/SUB
1189     switch (cast<Instruction>(CxtI->user_back())->getOpcode()) {
1190     case Instruction::Add:
1191     case Instruction::Sub:
1192     case Instruction::And:
1193     case Instruction::Xor:
1194     case Instruction::Or:
1195     case Instruction::ICmp:
1196       return true;
1197     default:
1198       return false;
1199     }
1200   };
1201   if (LooksLikeAFreeShift())
1202     return 0;
1203 
1204   int BaseCost = ST->hasMVEIntegerOps() && Ty->isVectorTy()
1205                      ? ST->getMVEVectorCostFactor()
1206                      : 1;
1207 
1208   // The rest of this mostly follows what is done in BaseT::getArithmeticInstrCost,
1209   // without treating floats as more expensive that scalars or increasing the
1210   // costs for custom operations. The results is also multiplied by the
1211   // MVEVectorCostFactor where appropriate.
1212   if (TLI->isOperationLegalOrCustomOrPromote(ISDOpcode, LT.second))
1213     return LT.first * BaseCost;
1214 
1215   // Else this is expand, assume that we need to scalarize this op.
1216   if (auto *VTy = dyn_cast<FixedVectorType>(Ty)) {
1217     unsigned Num = VTy->getNumElements();
1218     unsigned Cost = getArithmeticInstrCost(Opcode, Ty->getScalarType(),
1219                                            CostKind);
1220     // Return the cost of multiple scalar invocation plus the cost of
1221     // inserting and extracting the values.
1222     return BaseT::getScalarizationOverhead(VTy, Args) + Num * Cost;
1223   }
1224 
1225   return BaseCost;
1226 }
1227 
1228 int ARMTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
1229                                 MaybeAlign Alignment, unsigned AddressSpace,
1230                                 TTI::TargetCostKind CostKind,
1231                                 const Instruction *I) {
1232   // TODO: Handle other cost kinds.
1233   if (CostKind != TTI::TCK_RecipThroughput)
1234     return 1;
1235 
1236   // Type legalization can't handle structs
1237   if (TLI->getValueType(DL, Src, true) == MVT::Other)
1238     return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
1239                                   CostKind);
1240 
1241   if (ST->hasNEON() && Src->isVectorTy() &&
1242       (Alignment && *Alignment != Align(16)) &&
1243       cast<VectorType>(Src)->getElementType()->isDoubleTy()) {
1244     // Unaligned loads/stores are extremely inefficient.
1245     // We need 4 uops for vst.1/vld.1 vs 1uop for vldr/vstr.
1246     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
1247     return LT.first * 4;
1248   }
1249 
1250   // MVE can optimize a fpext(load(4xhalf)) using an extending integer load.
1251   // Same for stores.
1252   if (ST->hasMVEFloatOps() && isa<FixedVectorType>(Src) && I &&
1253       ((Opcode == Instruction::Load && I->hasOneUse() &&
1254         isa<FPExtInst>(*I->user_begin())) ||
1255        (Opcode == Instruction::Store && isa<FPTruncInst>(I->getOperand(0))))) {
1256     FixedVectorType *SrcVTy = cast<FixedVectorType>(Src);
1257     Type *DstTy =
1258         Opcode == Instruction::Load
1259             ? (*I->user_begin())->getType()
1260             : cast<Instruction>(I->getOperand(0))->getOperand(0)->getType();
1261     if (SrcVTy->getNumElements() == 4 && SrcVTy->getScalarType()->isHalfTy() &&
1262         DstTy->getScalarType()->isFloatTy())
1263       return ST->getMVEVectorCostFactor();
1264   }
1265 
1266   int BaseCost = ST->hasMVEIntegerOps() && Src->isVectorTy()
1267                      ? ST->getMVEVectorCostFactor()
1268                      : 1;
1269   return BaseCost * BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
1270                                            CostKind, I);
1271 }
1272 
1273 int ARMTTIImpl::getInterleavedMemoryOpCost(
1274     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
1275     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
1276     bool UseMaskForCond, bool UseMaskForGaps) {
1277   assert(Factor >= 2 && "Invalid interleave factor");
1278   assert(isa<VectorType>(VecTy) && "Expect a vector type");
1279 
1280   // vldN/vstN doesn't support vector types of i64/f64 element.
1281   bool EltIs64Bits = DL.getTypeSizeInBits(VecTy->getScalarType()) == 64;
1282 
1283   if (Factor <= TLI->getMaxSupportedInterleaveFactor() && !EltIs64Bits &&
1284       !UseMaskForCond && !UseMaskForGaps) {
1285     unsigned NumElts = cast<FixedVectorType>(VecTy)->getNumElements();
1286     auto *SubVecTy =
1287         FixedVectorType::get(VecTy->getScalarType(), NumElts / Factor);
1288 
1289     // vldN/vstN only support legal vector types of size 64 or 128 in bits.
1290     // Accesses having vector types that are a multiple of 128 bits can be
1291     // matched to more than one vldN/vstN instruction.
1292     int BaseCost = ST->hasMVEIntegerOps() ? ST->getMVEVectorCostFactor() : 1;
1293     if (NumElts % Factor == 0 &&
1294         TLI->isLegalInterleavedAccessType(Factor, SubVecTy, DL))
1295       return Factor * BaseCost * TLI->getNumInterleavedAccesses(SubVecTy, DL);
1296 
1297     // Some smaller than legal interleaved patterns are cheap as we can make
1298     // use of the vmovn or vrev patterns to interleave a standard load. This is
1299     // true for v4i8, v8i8 and v4i16 at least (but not for v4f16 as it is
1300     // promoted differently). The cost of 2 here is then a load and vrev or
1301     // vmovn.
1302     if (ST->hasMVEIntegerOps() && Factor == 2 && NumElts / Factor > 2 &&
1303         VecTy->isIntOrIntVectorTy() && DL.getTypeSizeInBits(SubVecTy) <= 64)
1304       return 2 * BaseCost;
1305   }
1306 
1307   return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
1308                                            Alignment, AddressSpace, CostKind,
1309                                            UseMaskForCond, UseMaskForGaps);
1310 }
1311 
1312 unsigned ARMTTIImpl::getGatherScatterOpCost(unsigned Opcode, Type *DataTy,
1313                                             const Value *Ptr, bool VariableMask,
1314                                             Align Alignment,
1315                                             TTI::TargetCostKind CostKind,
1316                                             const Instruction *I) {
1317   using namespace PatternMatch;
1318   if (!ST->hasMVEIntegerOps() || !EnableMaskedGatherScatters)
1319     return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
1320                                          Alignment, CostKind, I);
1321 
1322   assert(DataTy->isVectorTy() && "Can't do gather/scatters on scalar!");
1323   auto *VTy = cast<FixedVectorType>(DataTy);
1324 
1325   // TODO: Splitting, once we do that.
1326 
1327   unsigned NumElems = VTy->getNumElements();
1328   unsigned EltSize = VTy->getScalarSizeInBits();
1329   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, DataTy);
1330 
1331   // For now, it is assumed that for the MVE gather instructions the loads are
1332   // all effectively serialised. This means the cost is the scalar cost
1333   // multiplied by the number of elements being loaded. This is possibly very
1334   // conservative, but even so we still end up vectorising loops because the
1335   // cost per iteration for many loops is lower than for scalar loops.
1336   unsigned VectorCost = NumElems * LT.first * ST->getMVEVectorCostFactor();
1337   // The scalarization cost should be a lot higher. We use the number of vector
1338   // elements plus the scalarization overhead.
1339   unsigned ScalarCost =
1340       NumElems * LT.first + BaseT::getScalarizationOverhead(VTy, {});
1341 
1342   if (Alignment < EltSize / 8)
1343     return ScalarCost;
1344 
1345   unsigned ExtSize = EltSize;
1346   // Check whether there's a single user that asks for an extended type
1347   if (I != nullptr) {
1348     // Dependent of the caller of this function, a gather instruction will
1349     // either have opcode Instruction::Load or be a call to the masked_gather
1350     // intrinsic
1351     if ((I->getOpcode() == Instruction::Load ||
1352          match(I, m_Intrinsic<Intrinsic::masked_gather>())) &&
1353         I->hasOneUse()) {
1354       const User *Us = *I->users().begin();
1355       if (isa<ZExtInst>(Us) || isa<SExtInst>(Us)) {
1356         // only allow valid type combinations
1357         unsigned TypeSize =
1358             cast<Instruction>(Us)->getType()->getScalarSizeInBits();
1359         if (((TypeSize == 32 && (EltSize == 8 || EltSize == 16)) ||
1360              (TypeSize == 16 && EltSize == 8)) &&
1361             TypeSize * NumElems == 128) {
1362           ExtSize = TypeSize;
1363         }
1364       }
1365     }
1366     // Check whether the input data needs to be truncated
1367     TruncInst *T;
1368     if ((I->getOpcode() == Instruction::Store ||
1369          match(I, m_Intrinsic<Intrinsic::masked_scatter>())) &&
1370         (T = dyn_cast<TruncInst>(I->getOperand(0)))) {
1371       // Only allow valid type combinations
1372       unsigned TypeSize = T->getOperand(0)->getType()->getScalarSizeInBits();
1373       if (((EltSize == 16 && TypeSize == 32) ||
1374            (EltSize == 8 && (TypeSize == 32 || TypeSize == 16))) &&
1375           TypeSize * NumElems == 128)
1376         ExtSize = TypeSize;
1377     }
1378   }
1379 
1380   if (ExtSize * NumElems != 128 || NumElems < 4)
1381     return ScalarCost;
1382 
1383   // Any (aligned) i32 gather will not need to be scalarised.
1384   if (ExtSize == 32)
1385     return VectorCost;
1386   // For smaller types, we need to ensure that the gep's inputs are correctly
1387   // extended from a small enough value. Other sizes (including i64) are
1388   // scalarized for now.
1389   if (ExtSize != 8 && ExtSize != 16)
1390     return ScalarCost;
1391 
1392   if (const auto *BC = dyn_cast<BitCastInst>(Ptr))
1393     Ptr = BC->getOperand(0);
1394   if (const auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
1395     if (GEP->getNumOperands() != 2)
1396       return ScalarCost;
1397     unsigned Scale = DL.getTypeAllocSize(GEP->getResultElementType());
1398     // Scale needs to be correct (which is only relevant for i16s).
1399     if (Scale != 1 && Scale * 8 != ExtSize)
1400       return ScalarCost;
1401     // And we need to zext (not sext) the indexes from a small enough type.
1402     if (const auto *ZExt = dyn_cast<ZExtInst>(GEP->getOperand(1))) {
1403       if (ZExt->getOperand(0)->getType()->getScalarSizeInBits() <= ExtSize)
1404         return VectorCost;
1405     }
1406     return ScalarCost;
1407   }
1408   return ScalarCost;
1409 }
1410 
1411 bool ARMTTIImpl::isLoweredToCall(const Function *F) {
1412   if (!F->isIntrinsic())
1413     BaseT::isLoweredToCall(F);
1414 
1415   // Assume all Arm-specific intrinsics map to an instruction.
1416   if (F->getName().startswith("llvm.arm"))
1417     return false;
1418 
1419   switch (F->getIntrinsicID()) {
1420   default: break;
1421   case Intrinsic::powi:
1422   case Intrinsic::sin:
1423   case Intrinsic::cos:
1424   case Intrinsic::pow:
1425   case Intrinsic::log:
1426   case Intrinsic::log10:
1427   case Intrinsic::log2:
1428   case Intrinsic::exp:
1429   case Intrinsic::exp2:
1430     return true;
1431   case Intrinsic::sqrt:
1432   case Intrinsic::fabs:
1433   case Intrinsic::copysign:
1434   case Intrinsic::floor:
1435   case Intrinsic::ceil:
1436   case Intrinsic::trunc:
1437   case Intrinsic::rint:
1438   case Intrinsic::nearbyint:
1439   case Intrinsic::round:
1440   case Intrinsic::canonicalize:
1441   case Intrinsic::lround:
1442   case Intrinsic::llround:
1443   case Intrinsic::lrint:
1444   case Intrinsic::llrint:
1445     if (F->getReturnType()->isDoubleTy() && !ST->hasFP64())
1446       return true;
1447     if (F->getReturnType()->isHalfTy() && !ST->hasFullFP16())
1448       return true;
1449     // Some operations can be handled by vector instructions and assume
1450     // unsupported vectors will be expanded into supported scalar ones.
1451     // TODO Handle scalar operations properly.
1452     return !ST->hasFPARMv8Base() && !ST->hasVFP2Base();
1453   case Intrinsic::masked_store:
1454   case Intrinsic::masked_load:
1455   case Intrinsic::masked_gather:
1456   case Intrinsic::masked_scatter:
1457     return !ST->hasMVEIntegerOps();
1458   case Intrinsic::sadd_with_overflow:
1459   case Intrinsic::uadd_with_overflow:
1460   case Intrinsic::ssub_with_overflow:
1461   case Intrinsic::usub_with_overflow:
1462   case Intrinsic::sadd_sat:
1463   case Intrinsic::uadd_sat:
1464   case Intrinsic::ssub_sat:
1465   case Intrinsic::usub_sat:
1466     return false;
1467   }
1468 
1469   return BaseT::isLoweredToCall(F);
1470 }
1471 
1472 bool ARMTTIImpl::maybeLoweredToCall(Instruction &I) {
1473   unsigned ISD = TLI->InstructionOpcodeToISD(I.getOpcode());
1474   EVT VT = TLI->getValueType(DL, I.getType(), true);
1475   if (TLI->getOperationAction(ISD, VT) == TargetLowering::LibCall)
1476     return true;
1477 
1478   // Check if an intrinsic will be lowered to a call and assume that any
1479   // other CallInst will generate a bl.
1480   if (auto *Call = dyn_cast<CallInst>(&I)) {
1481     if (isa<IntrinsicInst>(Call)) {
1482       if (const Function *F = Call->getCalledFunction())
1483         return isLoweredToCall(F);
1484     }
1485     return true;
1486   }
1487 
1488   // FPv5 provides conversions between integer, double-precision,
1489   // single-precision, and half-precision formats.
1490   switch (I.getOpcode()) {
1491   default:
1492     break;
1493   case Instruction::FPToSI:
1494   case Instruction::FPToUI:
1495   case Instruction::SIToFP:
1496   case Instruction::UIToFP:
1497   case Instruction::FPTrunc:
1498   case Instruction::FPExt:
1499     return !ST->hasFPARMv8Base();
1500   }
1501 
1502   // FIXME: Unfortunately the approach of checking the Operation Action does
1503   // not catch all cases of Legalization that use library calls. Our
1504   // Legalization step categorizes some transformations into library calls as
1505   // Custom, Expand or even Legal when doing type legalization. So for now
1506   // we have to special case for instance the SDIV of 64bit integers and the
1507   // use of floating point emulation.
1508   if (VT.isInteger() && VT.getSizeInBits() >= 64) {
1509     switch (ISD) {
1510     default:
1511       break;
1512     case ISD::SDIV:
1513     case ISD::UDIV:
1514     case ISD::SREM:
1515     case ISD::UREM:
1516     case ISD::SDIVREM:
1517     case ISD::UDIVREM:
1518       return true;
1519     }
1520   }
1521 
1522   // Assume all other non-float operations are supported.
1523   if (!VT.isFloatingPoint())
1524     return false;
1525 
1526   // We'll need a library call to handle most floats when using soft.
1527   if (TLI->useSoftFloat()) {
1528     switch (I.getOpcode()) {
1529     default:
1530       return true;
1531     case Instruction::Alloca:
1532     case Instruction::Load:
1533     case Instruction::Store:
1534     case Instruction::Select:
1535     case Instruction::PHI:
1536       return false;
1537     }
1538   }
1539 
1540   // We'll need a libcall to perform double precision operations on a single
1541   // precision only FPU.
1542   if (I.getType()->isDoubleTy() && !ST->hasFP64())
1543     return true;
1544 
1545   // Likewise for half precision arithmetic.
1546   if (I.getType()->isHalfTy() && !ST->hasFullFP16())
1547     return true;
1548 
1549   return false;
1550 }
1551 
1552 bool ARMTTIImpl::isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
1553                                           AssumptionCache &AC,
1554                                           TargetLibraryInfo *LibInfo,
1555                                           HardwareLoopInfo &HWLoopInfo) {
1556   // Low-overhead branches are only supported in the 'low-overhead branch'
1557   // extension of v8.1-m.
1558   if (!ST->hasLOB() || DisableLowOverheadLoops) {
1559     LLVM_DEBUG(dbgs() << "ARMHWLoops: Disabled\n");
1560     return false;
1561   }
1562 
1563   if (!SE.hasLoopInvariantBackedgeTakenCount(L)) {
1564     LLVM_DEBUG(dbgs() << "ARMHWLoops: No BETC\n");
1565     return false;
1566   }
1567 
1568   const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1569   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
1570     LLVM_DEBUG(dbgs() << "ARMHWLoops: Uncomputable BETC\n");
1571     return false;
1572   }
1573 
1574   const SCEV *TripCountSCEV =
1575     SE.getAddExpr(BackedgeTakenCount,
1576                   SE.getOne(BackedgeTakenCount->getType()));
1577 
1578   // We need to store the trip count in LR, a 32-bit register.
1579   if (SE.getUnsignedRangeMax(TripCountSCEV).getBitWidth() > 32) {
1580     LLVM_DEBUG(dbgs() << "ARMHWLoops: Trip count does not fit into 32bits\n");
1581     return false;
1582   }
1583 
1584   // Making a call will trash LR and clear LO_BRANCH_INFO, so there's little
1585   // point in generating a hardware loop if that's going to happen.
1586 
1587   auto IsHardwareLoopIntrinsic = [](Instruction &I) {
1588     if (auto *Call = dyn_cast<IntrinsicInst>(&I)) {
1589       switch (Call->getIntrinsicID()) {
1590       default:
1591         break;
1592       case Intrinsic::set_loop_iterations:
1593       case Intrinsic::test_set_loop_iterations:
1594       case Intrinsic::loop_decrement:
1595       case Intrinsic::loop_decrement_reg:
1596         return true;
1597       }
1598     }
1599     return false;
1600   };
1601 
1602   // Scan the instructions to see if there's any that we know will turn into a
1603   // call or if this loop is already a low-overhead loop.
1604   auto ScanLoop = [&](Loop *L) {
1605     for (auto *BB : L->getBlocks()) {
1606       for (auto &I : *BB) {
1607         if (maybeLoweredToCall(I) || IsHardwareLoopIntrinsic(I)) {
1608           LLVM_DEBUG(dbgs() << "ARMHWLoops: Bad instruction: " << I << "\n");
1609           return false;
1610         }
1611       }
1612     }
1613     return true;
1614   };
1615 
1616   // Visit inner loops.
1617   for (auto Inner : *L)
1618     if (!ScanLoop(Inner))
1619       return false;
1620 
1621   if (!ScanLoop(L))
1622     return false;
1623 
1624   // TODO: Check whether the trip count calculation is expensive. If L is the
1625   // inner loop but we know it has a low trip count, calculating that trip
1626   // count (in the parent loop) may be detrimental.
1627 
1628   LLVMContext &C = L->getHeader()->getContext();
1629   HWLoopInfo.CounterInReg = true;
1630   HWLoopInfo.IsNestingLegal = false;
1631   HWLoopInfo.PerformEntryTest = true;
1632   HWLoopInfo.CountType = Type::getInt32Ty(C);
1633   HWLoopInfo.LoopDecrement = ConstantInt::get(HWLoopInfo.CountType, 1);
1634   return true;
1635 }
1636 
1637 static bool canTailPredicateInstruction(Instruction &I, int &ICmpCount) {
1638   // We don't allow icmp's, and because we only look at single block loops,
1639   // we simply count the icmps, i.e. there should only be 1 for the backedge.
1640   if (isa<ICmpInst>(&I) && ++ICmpCount > 1)
1641     return false;
1642 
1643   if (isa<FCmpInst>(&I))
1644     return false;
1645 
1646   // We could allow extending/narrowing FP loads/stores, but codegen is
1647   // too inefficient so reject this for now.
1648   if (isa<FPExtInst>(&I) || isa<FPTruncInst>(&I))
1649     return false;
1650 
1651   // Extends have to be extending-loads
1652   if (isa<SExtInst>(&I) || isa<ZExtInst>(&I) )
1653     if (!I.getOperand(0)->hasOneUse() || !isa<LoadInst>(I.getOperand(0)))
1654       return false;
1655 
1656   // Truncs have to be narrowing-stores
1657   if (isa<TruncInst>(&I) )
1658     if (!I.hasOneUse() || !isa<StoreInst>(*I.user_begin()))
1659       return false;
1660 
1661   return true;
1662 }
1663 
1664 // To set up a tail-predicated loop, we need to know the total number of
1665 // elements processed by that loop. Thus, we need to determine the element
1666 // size and:
1667 // 1) it should be uniform for all operations in the vector loop, so we
1668 //    e.g. don't want any widening/narrowing operations.
1669 // 2) it should be smaller than i64s because we don't have vector operations
1670 //    that work on i64s.
1671 // 3) we don't want elements to be reversed or shuffled, to make sure the
1672 //    tail-predication masks/predicates the right lanes.
1673 //
1674 static bool canTailPredicateLoop(Loop *L, LoopInfo *LI, ScalarEvolution &SE,
1675                                  const DataLayout &DL,
1676                                  const LoopAccessInfo *LAI) {
1677   LLVM_DEBUG(dbgs() << "Tail-predication: checking allowed instructions\n");
1678 
1679   // If there are live-out values, it is probably a reduction. We can predicate
1680   // most reduction operations freely under MVE using a combination of
1681   // prefer-predicated-reduction-select and inloop reductions. We limit this to
1682   // floating point and integer reductions, but don't check for operators
1683   // specifically here. If the value ends up not being a reduction (and so the
1684   // vectorizer cannot tailfold the loop), we should fall back to standard
1685   // vectorization automatically.
1686   SmallVector< Instruction *, 8 > LiveOuts;
1687   LiveOuts = llvm::findDefsUsedOutsideOfLoop(L);
1688   bool ReductionsDisabled =
1689       EnableTailPredication == TailPredication::EnabledNoReductions ||
1690       EnableTailPredication == TailPredication::ForceEnabledNoReductions;
1691 
1692   for (auto *I : LiveOuts) {
1693     if (!I->getType()->isIntegerTy() && !I->getType()->isFloatTy() &&
1694         !I->getType()->isHalfTy()) {
1695       LLVM_DEBUG(dbgs() << "Don't tail-predicate loop with non-integer/float "
1696                            "live-out value\n");
1697       return false;
1698     }
1699     if (ReductionsDisabled) {
1700       LLVM_DEBUG(dbgs() << "Reductions not enabled\n");
1701       return false;
1702     }
1703   }
1704 
1705   // Next, check that all instructions can be tail-predicated.
1706   PredicatedScalarEvolution PSE = LAI->getPSE();
1707   SmallVector<Instruction *, 16> LoadStores;
1708   int ICmpCount = 0;
1709 
1710   for (BasicBlock *BB : L->blocks()) {
1711     for (Instruction &I : BB->instructionsWithoutDebug()) {
1712       if (isa<PHINode>(&I))
1713         continue;
1714       if (!canTailPredicateInstruction(I, ICmpCount)) {
1715         LLVM_DEBUG(dbgs() << "Instruction not allowed: "; I.dump());
1716         return false;
1717       }
1718 
1719       Type *T  = I.getType();
1720       if (T->isPointerTy())
1721         T = T->getPointerElementType();
1722 
1723       if (T->getScalarSizeInBits() > 32) {
1724         LLVM_DEBUG(dbgs() << "Unsupported Type: "; T->dump());
1725         return false;
1726       }
1727       if (isa<StoreInst>(I) || isa<LoadInst>(I)) {
1728         Value *Ptr = isa<LoadInst>(I) ? I.getOperand(0) : I.getOperand(1);
1729         int64_t NextStride = getPtrStride(PSE, Ptr, L);
1730         if (NextStride == 1) {
1731           // TODO: for now only allow consecutive strides of 1. We could support
1732           // other strides as long as it is uniform, but let's keep it simple
1733           // for now.
1734           continue;
1735         } else if (NextStride == -1 ||
1736                    (NextStride == 2 && MVEMaxSupportedInterleaveFactor >= 2) ||
1737                    (NextStride == 4 && MVEMaxSupportedInterleaveFactor >= 4)) {
1738           LLVM_DEBUG(dbgs()
1739                      << "Consecutive strides of 2 found, vld2/vstr2 can't "
1740                         "be tail-predicated\n.");
1741           return false;
1742           // TODO: don't tail predicate if there is a reversed load?
1743         } else if (EnableMaskedGatherScatters) {
1744           // Gather/scatters do allow loading from arbitrary strides, at
1745           // least if they are loop invariant.
1746           // TODO: Loop variant strides should in theory work, too, but
1747           // this requires further testing.
1748           const SCEV *PtrScev =
1749               replaceSymbolicStrideSCEV(PSE, llvm::ValueToValueMap(), Ptr);
1750           if (auto AR = dyn_cast<SCEVAddRecExpr>(PtrScev)) {
1751             const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
1752             if (PSE.getSE()->isLoopInvariant(Step, L))
1753               continue;
1754           }
1755         }
1756         LLVM_DEBUG(dbgs() << "Bad stride found, can't "
1757                              "tail-predicate\n.");
1758         return false;
1759       }
1760     }
1761   }
1762 
1763   LLVM_DEBUG(dbgs() << "tail-predication: all instructions allowed!\n");
1764   return true;
1765 }
1766 
1767 bool ARMTTIImpl::preferPredicateOverEpilogue(Loop *L, LoopInfo *LI,
1768                                              ScalarEvolution &SE,
1769                                              AssumptionCache &AC,
1770                                              TargetLibraryInfo *TLI,
1771                                              DominatorTree *DT,
1772                                              const LoopAccessInfo *LAI) {
1773   if (!EnableTailPredication) {
1774     LLVM_DEBUG(dbgs() << "Tail-predication not enabled.\n");
1775     return false;
1776   }
1777 
1778   // Creating a predicated vector loop is the first step for generating a
1779   // tail-predicated hardware loop, for which we need the MVE masked
1780   // load/stores instructions:
1781   if (!ST->hasMVEIntegerOps())
1782     return false;
1783 
1784   // For now, restrict this to single block loops.
1785   if (L->getNumBlocks() > 1) {
1786     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: not a single block "
1787                          "loop.\n");
1788     return false;
1789   }
1790 
1791   assert(L->isInnermost() && "preferPredicateOverEpilogue: inner-loop expected");
1792 
1793   HardwareLoopInfo HWLoopInfo(L);
1794   if (!HWLoopInfo.canAnalyze(*LI)) {
1795     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not "
1796                          "analyzable.\n");
1797     return false;
1798   }
1799 
1800   // This checks if we have the low-overhead branch architecture
1801   // extension, and if we will create a hardware-loop:
1802   if (!isHardwareLoopProfitable(L, SE, AC, TLI, HWLoopInfo)) {
1803     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not "
1804                          "profitable.\n");
1805     return false;
1806   }
1807 
1808   if (!HWLoopInfo.isHardwareLoopCandidate(SE, *LI, *DT)) {
1809     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not "
1810                          "a candidate.\n");
1811     return false;
1812   }
1813 
1814   return canTailPredicateLoop(L, LI, SE, DL, LAI);
1815 }
1816 
1817 bool ARMTTIImpl::emitGetActiveLaneMask() const {
1818   if (!ST->hasMVEIntegerOps() || !EnableTailPredication)
1819     return false;
1820 
1821   // Intrinsic @llvm.get.active.lane.mask is supported.
1822   // It is used in the MVETailPredication pass, which requires the number of
1823   // elements processed by this vector loop to setup the tail-predicated
1824   // loop.
1825   return true;
1826 }
1827 void ARMTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
1828                                          TTI::UnrollingPreferences &UP) {
1829   // Only currently enable these preferences for M-Class cores.
1830   if (!ST->isMClass())
1831     return BasicTTIImplBase::getUnrollingPreferences(L, SE, UP);
1832 
1833   // Disable loop unrolling for Oz and Os.
1834   UP.OptSizeThreshold = 0;
1835   UP.PartialOptSizeThreshold = 0;
1836   if (L->getHeader()->getParent()->hasOptSize())
1837     return;
1838 
1839   // Only enable on Thumb-2 targets.
1840   if (!ST->isThumb2())
1841     return;
1842 
1843   SmallVector<BasicBlock*, 4> ExitingBlocks;
1844   L->getExitingBlocks(ExitingBlocks);
1845   LLVM_DEBUG(dbgs() << "Loop has:\n"
1846                     << "Blocks: " << L->getNumBlocks() << "\n"
1847                     << "Exit blocks: " << ExitingBlocks.size() << "\n");
1848 
1849   // Only allow another exit other than the latch. This acts as an early exit
1850   // as it mirrors the profitability calculation of the runtime unroller.
1851   if (ExitingBlocks.size() > 2)
1852     return;
1853 
1854   // Limit the CFG of the loop body for targets with a branch predictor.
1855   // Allowing 4 blocks permits if-then-else diamonds in the body.
1856   if (ST->hasBranchPredictor() && L->getNumBlocks() > 4)
1857     return;
1858 
1859   // Scan the loop: don't unroll loops with calls as this could prevent
1860   // inlining.
1861   unsigned Cost = 0;
1862   for (auto *BB : L->getBlocks()) {
1863     for (auto &I : *BB) {
1864       // Don't unroll vectorised loop. MVE does not benefit from it as much as
1865       // scalar code.
1866       if (I.getType()->isVectorTy())
1867         return;
1868 
1869       if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
1870         if (const Function *F = cast<CallBase>(I).getCalledFunction()) {
1871           if (!isLoweredToCall(F))
1872             continue;
1873         }
1874         return;
1875       }
1876 
1877       SmallVector<const Value*, 4> Operands(I.value_op_begin(),
1878                                             I.value_op_end());
1879       Cost +=
1880         getUserCost(&I, Operands, TargetTransformInfo::TCK_SizeAndLatency);
1881     }
1882   }
1883 
1884   LLVM_DEBUG(dbgs() << "Cost of loop: " << Cost << "\n");
1885 
1886   UP.Partial = true;
1887   UP.Runtime = true;
1888   UP.UpperBound = true;
1889   UP.UnrollRemainder = true;
1890   UP.DefaultUnrollRuntimeCount = 4;
1891   UP.UnrollAndJam = true;
1892   UP.UnrollAndJamInnerLoopThreshold = 60;
1893 
1894   // Force unrolling small loops can be very useful because of the branch
1895   // taken cost of the backedge.
1896   if (Cost < 12)
1897     UP.Force = true;
1898 }
1899 
1900 void ARMTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
1901                                        TTI::PeelingPreferences &PP) {
1902   BaseT::getPeelingPreferences(L, SE, PP);
1903 }
1904 
1905 bool ARMTTIImpl::useReductionIntrinsic(unsigned Opcode, Type *Ty,
1906                                        TTI::ReductionFlags Flags) const {
1907   return ST->hasMVEIntegerOps();
1908 }
1909 
1910 bool ARMTTIImpl::preferInLoopReduction(unsigned Opcode, Type *Ty,
1911                                        TTI::ReductionFlags Flags) const {
1912   if (!ST->hasMVEIntegerOps())
1913     return false;
1914 
1915   unsigned ScalarBits = Ty->getScalarSizeInBits();
1916   switch (Opcode) {
1917   case Instruction::Add:
1918     return ScalarBits <= 32;
1919   default:
1920     return false;
1921   }
1922 }
1923 
1924 bool ARMTTIImpl::preferPredicatedReductionSelect(
1925     unsigned Opcode, Type *Ty, TTI::ReductionFlags Flags) const {
1926   if (!ST->hasMVEIntegerOps())
1927     return false;
1928   return true;
1929 }
1930