LLVM 24.0.0git
ARMTargetTransformInfo.cpp
Go to the documentation of this file.
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
10#include "ARMSubtarget.h"
12#include "llvm/ADT/APInt.h"
19#include "llvm/IR/BasicBlock.h"
20#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/Instruction.h"
25#include "llvm/IR/Intrinsics.h"
26#include "llvm/IR/IntrinsicsARM.h"
28#include "llvm/IR/Type.h"
37#include <algorithm>
38#include <cassert>
39#include <cstdint>
40#include <optional>
41#include <utility>
42
43using namespace llvm;
44
45#define DEBUG_TYPE "armtti"
46
47/// Convert a vector load intrinsic into a simple llvm load instruction.
48/// This is beneficial when the underlying object being addressed comes
49/// from a constant, since we get constant-folding for free.
50static Value *simplifyNeonVld1(const IntrinsicInst &II, unsigned MemAlign,
51 InstCombiner::BuilderTy &Builder) {
52 auto *IntrAlign = dyn_cast<ConstantInt>(II.getArgOperand(1));
53
54 if (!IntrAlign)
55 return nullptr;
56
57 unsigned Alignment = IntrAlign->getLimitedValue() < MemAlign
58 ? MemAlign
59 : IntrAlign->getLimitedValue();
60
61 if (!isPowerOf2_32(Alignment))
62 return nullptr;
63
64 return Builder.CreateAlignedLoad(II.getType(), II.getArgOperand(0),
65 Align(Alignment));
66}
67
70 ScalarEvolution *SE) const {
71 if (ST->hasMVEIntegerOps())
73
74 if (L->getHeader()->getParent()->hasOptSize())
75 return TTI::AMK_None;
76
77 if (ST->isMClass() && ST->isThumb2() &&
78 L->getNumBlocks() == 1)
80
81 return TTI::AMK_None;
82}
83
84std::optional<Instruction *>
86 using namespace PatternMatch;
87 Intrinsic::ID IID = II.getIntrinsicID();
88 switch (IID) {
89 default:
90 break;
91 case Intrinsic::arm_neon_vld1: {
92 Align MemAlign =
93 getKnownAlignment(II.getArgOperand(0), IC.getDataLayout(), &II,
95 if (Value *V = simplifyNeonVld1(II, MemAlign.value(), IC.Builder)) {
96 return IC.replaceInstUsesWith(II, V);
97 }
98 break;
99 }
100
101 case Intrinsic::arm_neon_vld2:
102 case Intrinsic::arm_neon_vld3:
103 case Intrinsic::arm_neon_vld4:
104 case Intrinsic::arm_neon_vld2lane:
105 case Intrinsic::arm_neon_vld3lane:
106 case Intrinsic::arm_neon_vld4lane:
107 case Intrinsic::arm_neon_vst1:
108 case Intrinsic::arm_neon_vst2:
109 case Intrinsic::arm_neon_vst3:
110 case Intrinsic::arm_neon_vst4:
111 case Intrinsic::arm_neon_vst2lane:
112 case Intrinsic::arm_neon_vst3lane:
113 case Intrinsic::arm_neon_vst4lane: {
114 Align MemAlign =
115 getKnownAlignment(II.getArgOperand(0), IC.getDataLayout(), &II,
117 unsigned AlignArg = II.arg_size() - 1;
118 Value *AlignArgOp = II.getArgOperand(AlignArg);
119 MaybeAlign Align = cast<ConstantInt>(AlignArgOp)->getMaybeAlignValue();
120 if (Align && *Align < MemAlign) {
121 return IC.replaceOperand(
122 II, AlignArg,
123 ConstantInt::get(Type::getInt32Ty(II.getContext()), MemAlign.value(),
124 false));
125 }
126 break;
127 }
128
129 case Intrinsic::arm_neon_vld1x2:
130 case Intrinsic::arm_neon_vld1x3:
131 case Intrinsic::arm_neon_vld1x4:
132 case Intrinsic::arm_neon_vst1x2:
133 case Intrinsic::arm_neon_vst1x3:
134 case Intrinsic::arm_neon_vst1x4: {
135 Align NewAlign =
136 getKnownAlignment(II.getArgOperand(0), IC.getDataLayout(), &II,
138 Align OldAlign = II.getParamAlign(0).valueOrOne();
139 if (NewAlign > OldAlign)
140 II.addParamAttr(0,
141 Attribute::getWithAlignment(II.getContext(), NewAlign));
142 break;
143 }
144
145 case Intrinsic::arm_mve_pred_i2v: {
146 Value *Arg = II.getArgOperand(0);
147 Value *ArgArg;
149 PatternMatch::m_Value(ArgArg))) &&
150 II.getType() == ArgArg->getType()) {
151 return IC.replaceInstUsesWith(II, ArgArg);
152 }
153 Constant *XorMask;
155 PatternMatch::m_Value(ArgArg)),
156 PatternMatch::m_Constant(XorMask))) &&
157 II.getType() == ArgArg->getType()) {
158 if (auto *CI = dyn_cast<ConstantInt>(XorMask)) {
159 if (CI->getValue().trunc(16).isAllOnes()) {
160 auto TrueVector = IC.Builder.CreateVectorSplat(
161 cast<FixedVectorType>(II.getType())->getNumElements(),
162 IC.Builder.getTrue());
163 return BinaryOperator::Create(Instruction::Xor, ArgArg, TrueVector);
164 }
165 }
166 }
167 KnownBits ScalarKnown(32);
168 if (IC.SimplifyDemandedBits(&II, 0, APInt::getLowBitsSet(32, 16),
169 ScalarKnown)) {
170 return &II;
171 }
172 break;
173 }
174 case Intrinsic::arm_mve_pred_v2i: {
175 Value *Arg = II.getArgOperand(0);
176 Value *ArgArg;
178 PatternMatch::m_Value(ArgArg)))) {
179 return IC.replaceInstUsesWith(II, ArgArg);
180 }
181
182 if (II.getMetadata(LLVMContext::MD_range))
183 break;
184
185 ConstantRange Range(APInt(32, 0), APInt(32, 0x10000));
186
187 if (auto CurrentRange = II.getRange()) {
188 Range = Range.intersectWith(*CurrentRange);
189 if (Range == CurrentRange)
190 break;
191 }
192
193 II.addRangeRetAttr(Range);
194 II.addRetAttr(Attribute::NoUndef);
195 return &II;
196 }
197 case Intrinsic::arm_mve_vadc:
198 case Intrinsic::arm_mve_vadc_predicated: {
199 unsigned CarryOp =
200 (II.getIntrinsicID() == Intrinsic::arm_mve_vadc_predicated) ? 3 : 2;
201 assert(II.getArgOperand(CarryOp)->getType()->getScalarSizeInBits() == 32 &&
202 "Bad type for intrinsic!");
203
204 KnownBits CarryKnown(32);
205 if (IC.SimplifyDemandedBits(&II, CarryOp, APInt::getOneBitSet(32, 29),
206 CarryKnown)) {
207 return &II;
208 }
209 break;
210 }
211 case Intrinsic::arm_mve_vmldava: {
213 if (I->hasOneUse()) {
214 auto *User = *I->user_begin();
215 Value *OpZ;
216 if (match(User, m_c_Add(m_Specific(I), m_Value(OpZ))) &&
217 match(I->getOperand(3), m_Zero())) {
218 Value *OpX = I->getOperand(4);
219 Value *OpY = I->getOperand(5);
220 Type *OpTy = OpX->getType();
221
223 Value *V =
224 IC.Builder.CreateIntrinsic(Intrinsic::arm_mve_vmldava, {OpTy},
225 {I->getOperand(0), I->getOperand(1),
226 I->getOperand(2), OpZ, OpX, OpY});
227
229 return IC.eraseInstFromFunction(*User);
230 }
231 }
232 return std::nullopt;
233 }
234 }
235 return std::nullopt;
236}
237
239 InstCombiner &IC, IntrinsicInst &II, APInt OrigDemandedElts,
240 APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3,
241 std::function<void(Instruction *, unsigned, APInt, APInt &)>
242 SimplifyAndSetOp) const {
243
244 // Compute the demanded bits for a narrowing MVE intrinsic. The TopOpc is the
245 // opcode specifying a Top/Bottom instruction, which can change between
246 // instructions.
247 auto SimplifyNarrowInstrTopBottom =[&](unsigned TopOpc) {
248 unsigned NumElts = cast<FixedVectorType>(II.getType())->getNumElements();
249 unsigned IsTop = cast<ConstantInt>(II.getOperand(TopOpc))->getZExtValue();
250
251 // The only odd/even lanes of operand 0 will only be demanded depending
252 // on whether this is a top/bottom instruction.
253 APInt DemandedElts =
254 APInt::getSplat(NumElts, IsTop ? APInt::getLowBitsSet(2, 1)
255 : APInt::getHighBitsSet(2, 1));
256 SimplifyAndSetOp(&II, 0, OrigDemandedElts & DemandedElts, UndefElts);
257 // The other lanes will be defined from the inserted elements.
258 UndefElts &= APInt::getSplat(NumElts, IsTop ? APInt::getLowBitsSet(2, 1)
259 : APInt::getHighBitsSet(2, 1));
260 return std::nullopt;
261 };
262
263 switch (II.getIntrinsicID()) {
264 default:
265 break;
266 case Intrinsic::arm_mve_vcvt_narrow:
267 SimplifyNarrowInstrTopBottom(2);
268 break;
269 case Intrinsic::arm_mve_vqmovn:
270 SimplifyNarrowInstrTopBottom(4);
271 break;
272 case Intrinsic::arm_mve_vshrn:
273 SimplifyNarrowInstrTopBottom(7);
274 break;
275 }
276
277 return std::nullopt;
278}
279
281 TTI::TargetCostKind CostKind) const {
282 assert(Ty->isIntegerTy());
283
284 unsigned Bits = Ty->getPrimitiveSizeInBits();
285 if (Bits == 0 || Imm.getActiveBits() >= 64)
286 return 4;
287
288 int64_t SImmVal = Imm.getSExtValue();
289 uint64_t ZImmVal = Imm.getZExtValue();
290 if (!ST->isThumb()) {
291 if ((SImmVal >= 0 && SImmVal < 65536) ||
292 (ARM_AM::getSOImmVal(ZImmVal) != -1) ||
293 (ARM_AM::getSOImmVal(~ZImmVal) != -1))
294 return 1;
295 return ST->hasV6T2Ops() ? 2 : 3;
296 }
297 if (ST->isThumb2()) {
298 if ((SImmVal >= 0 && SImmVal < 65536) ||
299 (ARM_AM::getT2SOImmVal(ZImmVal) != -1) ||
300 (ARM_AM::getT2SOImmVal(~ZImmVal) != -1))
301 return 1;
302 return ST->hasV6T2Ops() ? 2 : 3;
303 }
304 // Thumb1, any i8 imm cost 1.
305 if (Bits == 8 || (SImmVal >= 0 && SImmVal < 256))
306 return 1;
307 if ((~SImmVal < 256) || ARM_AM::isThumbImmShiftedVal(ZImmVal))
308 return 2;
309 // Load from constantpool.
310 return 3;
311}
312
313// Constants smaller than 256 fit in the immediate field of
314// Thumb1 instructions so we return a zero cost and 1 otherwise.
316 const APInt &Imm,
317 Type *Ty) const {
318 if (Imm.isNonNegative() && Imm.getLimitedValue() < 256)
319 return 0;
320
321 return 1;
322}
323
324// Checks whether Inst is part of a min(max()) or max(min()) pattern
325// that will match to an SSAT instruction. Returns the instruction being
326// saturated, or null if no saturation pattern was found.
328 Value *LHS, *RHS;
329 ConstantInt *C;
331
332 if (InstSPF == SPF_SMAX &&
334 C->getValue() == Imm && Imm.isNegative() && Imm.isNegatedPowerOf2()) {
335
336 auto isSSatMin = [&](Value *MinInst) {
337 if (isa<SelectInst>(MinInst)) {
338 Value *MinLHS, *MinRHS;
339 ConstantInt *MinC;
340 SelectPatternFlavor MinSPF =
341 matchSelectPattern(MinInst, MinLHS, MinRHS).Flavor;
342 if (MinSPF == SPF_SMIN &&
344 MinC->getValue() == ((-Imm) - 1))
345 return true;
346 }
347 return false;
348 };
349
350 if (isSSatMin(Inst->getOperand(1)))
351 return cast<Instruction>(Inst->getOperand(1))->getOperand(1);
352 if (Inst->hasNUses(2) &&
353 (isSSatMin(*Inst->user_begin()) || isSSatMin(*(++Inst->user_begin()))))
354 return Inst->getOperand(1);
355 }
356 return nullptr;
357}
358
359// Look for a FP Saturation pattern, where the instruction can be simplified to
360// a fptosi.sat. max(min(fptosi)). The constant in this case is always free.
361static bool isFPSatMinMaxPattern(Instruction *Inst, const APInt &Imm) {
362 if (Imm.getBitWidth() != 64 ||
363 Imm != APInt::getHighBitsSet(64, 33)) // -2147483648
364 return false;
366 if (!FP && isa<ICmpInst>(Inst) && Inst->hasOneUse())
368 if (!FP)
369 return false;
370 return isa<FPToSIInst>(FP);
371}
372
373InstructionCost ARMTTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
374 const APInt &Imm, Type *Ty,
375 TTI::TargetCostKind CostKind,
376 Instruction *Inst) const {
377 // Division by a constant can be turned into multiplication, but only if we
378 // know it's constant. So it's not so much that the immediate is cheap (it's
379 // not), but that the alternative is worse.
380 // FIXME: this is probably unneeded with GlobalISel.
381 if ((Opcode == Instruction::SDiv || Opcode == Instruction::UDiv ||
382 Opcode == Instruction::SRem || Opcode == Instruction::URem) &&
383 Idx == 1)
384 return 0;
385
386 // Leave any gep offsets for the CodeGenPrepare, which will do a better job at
387 // splitting any large offsets.
388 if (Opcode == Instruction::GetElementPtr && Idx != 0)
389 return 0;
390
391 if (Opcode == Instruction::And) {
392 // UXTB/UXTH
393 if (Imm == 255 || Imm == 65535)
394 return 0;
395 // Conversion to BIC is free, and means we can use ~Imm instead.
396 return std::min(getIntImmCost(Imm, Ty, CostKind),
397 getIntImmCost(~Imm, Ty, CostKind));
398 }
399
400 if (Opcode == Instruction::Add)
401 // Conversion to SUB is free, and means we can use -Imm instead.
402 return std::min(getIntImmCost(Imm, Ty, CostKind),
403 getIntImmCost(-Imm, Ty, CostKind));
404
405 if (Opcode == Instruction::ICmp && Imm.isNegative() &&
406 Ty->getIntegerBitWidth() == 32) {
407 int64_t NegImm = -Imm.getSExtValue();
408 if (ST->isThumb2() && NegImm < 1<<12)
409 // icmp X, #-C -> cmn X, #C
410 return 0;
411 if (ST->isThumb() && NegImm < 1<<8)
412 // icmp X, #-C -> adds X, #C
413 return 0;
414 }
415
416 // xor a, -1 can always be folded to MVN
417 if (Opcode == Instruction::Xor && Imm.isAllOnes())
418 return 0;
419
420 // Ensures negative constant of min(max()) or max(min()) patterns that
421 // match to SSAT instructions don't get hoisted
422 if (Inst && ((ST->hasV6Ops() && !ST->isThumb()) || ST->isThumb2()) &&
423 Ty->getIntegerBitWidth() <= 32) {
424 if (isSSATMinMaxPattern(Inst, Imm) ||
425 (isa<ICmpInst>(Inst) && Inst->hasOneUse() &&
427 return 0;
428 }
429
430 if (Inst && ST->hasVFP2Base() && isFPSatMinMaxPattern(Inst, Imm))
431 return 0;
432
433 // We can convert <= -1 to < 0, which is generally quite cheap.
434 if (Inst && Opcode == Instruction::ICmp && Idx == 1 && Imm.isAllOnes()) {
435 ICmpInst::Predicate Pred = cast<ICmpInst>(Inst)->getPredicate();
436 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE)
437 return std::min(getIntImmCost(Imm, Ty, CostKind),
438 getIntImmCost(Imm + 1, Ty, CostKind));
439 }
440
441 return getIntImmCost(Imm, Ty, CostKind);
442}
443
445 TTI::TargetCostKind CostKind,
446 const Instruction *I) const {
447 if (CostKind == TTI::TCK_RecipThroughput &&
448 (ST->hasNEON() || ST->hasMVEIntegerOps())) {
449 // FIXME: The vectorizer is highly sensitive to the cost of these
450 // instructions, which suggests that it may be using the costs incorrectly.
451 // But, for now, just make them free to avoid performance regressions for
452 // vector targets.
453 return 0;
454 }
455 return BaseT::getCFInstrCost(Opcode, CostKind, I);
456}
457
459 Type *Src,
461 TTI::TargetCostKind CostKind,
462 const Instruction *I) const {
463 int ISD = TLI->InstructionOpcodeToISD(Opcode);
464 assert(ISD && "Invalid opcode");
465
466 // TODO: Allow non-throughput costs that aren't binary.
467 auto AdjustCost = [&CostKind](InstructionCost Cost) -> InstructionCost {
468 if (CostKind != TTI::TCK_RecipThroughput)
469 return Cost == 0 ? 0 : 1;
470 return Cost;
471 };
472 auto IsLegalFPType = [this](EVT VT) {
473 EVT EltVT = VT.getScalarType();
474 return (EltVT == MVT::f32 && ST->hasVFP2Base()) ||
475 (EltVT == MVT::f64 && ST->hasFP64()) ||
476 (EltVT == MVT::f16 && ST->hasFullFP16());
477 };
478
479 EVT SrcTy = TLI->getValueType(DL, Src);
480 EVT DstTy = TLI->getValueType(DL, Dst);
481
482 if (!SrcTy.isSimple() || !DstTy.isSimple())
483 return AdjustCost(
484 BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
485
486 // Extending masked load/Truncating masked stores is expensive because we
487 // currently don't split them. This means that we'll likely end up
488 // loading/storing each element individually (hence the high cost).
489 if ((ST->hasMVEIntegerOps() &&
490 (Opcode == Instruction::Trunc || Opcode == Instruction::ZExt ||
491 Opcode == Instruction::SExt)) ||
492 (ST->hasMVEFloatOps() &&
493 (Opcode == Instruction::FPExt || Opcode == Instruction::FPTrunc) &&
494 IsLegalFPType(SrcTy) && IsLegalFPType(DstTy)))
495 if (CCH == TTI::CastContextHint::Masked && DstTy.getSizeInBits() > 128)
496 return 2 * DstTy.getVectorNumElements() *
497 ST->getMVEVectorCostFactor(CostKind);
498
499 // The extend of other kinds of load is free
500 if (CCH == TTI::CastContextHint::Normal ||
502 static const TypeConversionCostTblEntry LoadConversionTbl[] = {
503 {ISD::SIGN_EXTEND, MVT::i32, MVT::i16, 0},
504 {ISD::ZERO_EXTEND, MVT::i32, MVT::i16, 0},
505 {ISD::SIGN_EXTEND, MVT::i32, MVT::i8, 0},
506 {ISD::ZERO_EXTEND, MVT::i32, MVT::i8, 0},
507 {ISD::SIGN_EXTEND, MVT::i16, MVT::i8, 0},
508 {ISD::ZERO_EXTEND, MVT::i16, MVT::i8, 0},
509 {ISD::SIGN_EXTEND, MVT::i64, MVT::i32, 1},
510 {ISD::ZERO_EXTEND, MVT::i64, MVT::i32, 1},
511 {ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 1},
512 {ISD::ZERO_EXTEND, MVT::i64, MVT::i16, 1},
513 {ISD::SIGN_EXTEND, MVT::i64, MVT::i8, 1},
514 {ISD::ZERO_EXTEND, MVT::i64, MVT::i8, 1},
515 };
516 if (const auto *Entry = ConvertCostTableLookup(
517 LoadConversionTbl, ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
518 return AdjustCost(Entry->Cost);
519
520 static const TypeConversionCostTblEntry MVELoadConversionTbl[] = {
521 {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 0},
522 {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 0},
523 {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 0},
524 {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 0},
525 {ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 0},
526 {ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 0},
527 // The following extend from a legal type to an illegal type, so need to
528 // split the load. This introduced an extra load operation, but the
529 // extend is still "free".
530 {ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 1},
531 {ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 1},
532 {ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 3},
533 {ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 3},
534 {ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 1},
535 {ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 1},
536 };
537 if (SrcTy.isVector() && ST->hasMVEIntegerOps()) {
538 if (const auto *Entry =
539 ConvertCostTableLookup(MVELoadConversionTbl, ISD,
540 DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
541 return Entry->Cost * ST->getMVEVectorCostFactor(CostKind);
542 }
543
544 static const TypeConversionCostTblEntry MVEFLoadConversionTbl[] = {
545 // FPExtends are similar but also require the VCVT instructions.
546 {ISD::FP_EXTEND, MVT::v4f32, MVT::v4f16, 1},
547 {ISD::FP_EXTEND, MVT::v8f32, MVT::v8f16, 3},
548 };
549 if (SrcTy.isVector() && ST->hasMVEFloatOps()) {
550 if (const auto *Entry =
551 ConvertCostTableLookup(MVEFLoadConversionTbl, ISD,
552 DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
553 return Entry->Cost * ST->getMVEVectorCostFactor(CostKind);
554 }
555
556 // The truncate of a store is free. This is the mirror of extends above.
557 static const TypeConversionCostTblEntry MVEStoreConversionTbl[] = {
558 {ISD::TRUNCATE, MVT::v4i32, MVT::v4i16, 0},
559 {ISD::TRUNCATE, MVT::v4i32, MVT::v4i8, 0},
560 {ISD::TRUNCATE, MVT::v8i16, MVT::v8i8, 0},
561 {ISD::TRUNCATE, MVT::v8i32, MVT::v8i16, 1},
562 {ISD::TRUNCATE, MVT::v8i32, MVT::v8i8, 1},
563 {ISD::TRUNCATE, MVT::v16i32, MVT::v16i8, 3},
564 {ISD::TRUNCATE, MVT::v16i16, MVT::v16i8, 1},
565 };
566 if (SrcTy.isVector() && ST->hasMVEIntegerOps()) {
567 if (const auto *Entry =
568 ConvertCostTableLookup(MVEStoreConversionTbl, ISD,
569 SrcTy.getSimpleVT(), DstTy.getSimpleVT()))
570 return Entry->Cost * ST->getMVEVectorCostFactor(CostKind);
571 }
572
573 static const TypeConversionCostTblEntry MVEFStoreConversionTbl[] = {
574 {ISD::FP_ROUND, MVT::v4f32, MVT::v4f16, 1},
575 {ISD::FP_ROUND, MVT::v8f32, MVT::v8f16, 3},
576 };
577 if (SrcTy.isVector() && ST->hasMVEFloatOps()) {
578 if (const auto *Entry =
579 ConvertCostTableLookup(MVEFStoreConversionTbl, ISD,
580 SrcTy.getSimpleVT(), DstTy.getSimpleVT()))
581 return Entry->Cost * ST->getMVEVectorCostFactor(CostKind);
582 }
583 }
584
585 // NEON vector operations that can extend their inputs.
586 if ((ISD == ISD::SIGN_EXTEND || ISD == ISD::ZERO_EXTEND) &&
587 I && I->hasOneUse() && ST->hasNEON() && SrcTy.isVector()) {
588 static const TypeConversionCostTblEntry NEONDoubleWidthTbl[] = {
589 // vaddl
590 { ISD::ADD, MVT::v4i32, MVT::v4i16, 0 },
591 { ISD::ADD, MVT::v8i16, MVT::v8i8, 0 },
592 // vsubl
593 { ISD::SUB, MVT::v4i32, MVT::v4i16, 0 },
594 { ISD::SUB, MVT::v8i16, MVT::v8i8, 0 },
595 // vmull
596 { ISD::MUL, MVT::v4i32, MVT::v4i16, 0 },
597 { ISD::MUL, MVT::v8i16, MVT::v8i8, 0 },
598 // vshll
599 { ISD::SHL, MVT::v4i32, MVT::v4i16, 0 },
600 { ISD::SHL, MVT::v8i16, MVT::v8i8, 0 },
601 };
602
603 auto *User = *I->user_begin();
604 int UserISD = TLI->InstructionOpcodeToISD(User->getOpcode());
605 if (auto *Entry = ConvertCostTableLookup(NEONDoubleWidthTbl, UserISD,
606 DstTy.getSimpleVT(),
607 SrcTy.getSimpleVT())) {
608 return AdjustCost(Entry->Cost);
609 }
610 }
611
612 // Single to/from double precision conversions.
613 if (Src->isVectorTy() && ST->hasNEON() &&
614 ((ISD == ISD::FP_ROUND && SrcTy.getScalarType() == MVT::f64 &&
615 DstTy.getScalarType() == MVT::f32) ||
616 (ISD == ISD::FP_EXTEND && SrcTy.getScalarType() == MVT::f32 &&
617 DstTy.getScalarType() == MVT::f64))) {
618 static const CostTblEntry NEONFltDblTbl[] = {
619 // Vector fptrunc/fpext conversions.
620 {ISD::FP_ROUND, MVT::v2f64, 2},
621 {ISD::FP_EXTEND, MVT::v2f32, 2},
622 {ISD::FP_EXTEND, MVT::v4f32, 4}};
623
624 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Src);
625 if (const auto *Entry = CostTableLookup(NEONFltDblTbl, ISD, LT.second))
626 return AdjustCost(LT.first * Entry->Cost);
627 }
628
629 // Some arithmetic, load and store operations have specific instructions
630 // to cast up/down their types automatically at no extra cost.
631 // TODO: Get these tables to know at least what the related operations are.
632 static const TypeConversionCostTblEntry NEONVectorConversionTbl[] = {
633 { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
634 { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
635 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 1 },
636 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 1 },
637 { ISD::TRUNCATE, MVT::v4i32, MVT::v4i64, 0 },
638 { ISD::TRUNCATE, MVT::v4i16, MVT::v4i32, 1 },
639
640 // The number of vmovl instructions for the extension.
641 { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
642 { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
643 { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
644 { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
645 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i8, 3 },
646 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i8, 3 },
647 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i16, 2 },
648 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i16, 2 },
649 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
650 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
651 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
652 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
653 { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
654 { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
655 { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
656 { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
657 { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
658 { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
659
660 // Operations that we legalize using splitting.
661 { ISD::TRUNCATE, MVT::v16i8, MVT::v16i32, 6 },
662 { ISD::TRUNCATE, MVT::v8i8, MVT::v8i32, 3 },
663
664 // Vector float <-> i32 conversions.
665 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
666 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
667
668 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i8, 3 },
669 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i8, 3 },
670 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i16, 2 },
671 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i16, 2 },
672 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
673 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
674 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i1, 3 },
675 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i1, 3 },
676 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8, 3 },
677 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8, 3 },
678 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
679 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
680 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
681 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
682 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i32, 2 },
683 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i32, 2 },
684 { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i16, 8 },
685 { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i16, 8 },
686 { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i32, 4 },
687 { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i32, 4 },
688
689 { ISD::FP_TO_SINT, MVT::v4i32, MVT::v4f32, 1 },
690 { ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f32, 1 },
691 { ISD::FP_TO_SINT, MVT::v4i8, MVT::v4f32, 3 },
692 { ISD::FP_TO_UINT, MVT::v4i8, MVT::v4f32, 3 },
693 { ISD::FP_TO_SINT, MVT::v4i16, MVT::v4f32, 2 },
694 { ISD::FP_TO_UINT, MVT::v4i16, MVT::v4f32, 2 },
695
696 // Vector double <-> i32 conversions.
697 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
698 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
699
700 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i8, 4 },
701 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i8, 4 },
702 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i16, 3 },
703 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i16, 3 },
704 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
705 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
706
707 { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f64, 2 },
708 { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f64, 2 },
709 { ISD::FP_TO_SINT, MVT::v8i16, MVT::v8f32, 4 },
710 { ISD::FP_TO_UINT, MVT::v8i16, MVT::v8f32, 4 },
711 { ISD::FP_TO_SINT, MVT::v16i16, MVT::v16f32, 8 },
712 { ISD::FP_TO_UINT, MVT::v16i16, MVT::v16f32, 8 }
713 };
714
715 if (SrcTy.isVector() && ST->hasNEON()) {
716 if (const auto *Entry = ConvertCostTableLookup(NEONVectorConversionTbl, ISD,
717 DstTy.getSimpleVT(),
718 SrcTy.getSimpleVT()))
719 return AdjustCost(Entry->Cost);
720 }
721
722 // Scalar float to integer conversions.
723 static const TypeConversionCostTblEntry NEONFloatConversionTbl[] = {
724 { ISD::FP_TO_SINT, MVT::i1, MVT::f32, 2 },
725 { ISD::FP_TO_UINT, MVT::i1, MVT::f32, 2 },
726 { ISD::FP_TO_SINT, MVT::i1, MVT::f64, 2 },
727 { ISD::FP_TO_UINT, MVT::i1, MVT::f64, 2 },
728 { ISD::FP_TO_SINT, MVT::i8, MVT::f32, 2 },
729 { ISD::FP_TO_UINT, MVT::i8, MVT::f32, 2 },
730 { ISD::FP_TO_SINT, MVT::i8, MVT::f64, 2 },
731 { ISD::FP_TO_UINT, MVT::i8, MVT::f64, 2 },
732 { ISD::FP_TO_SINT, MVT::i16, MVT::f32, 2 },
733 { ISD::FP_TO_UINT, MVT::i16, MVT::f32, 2 },
734 { ISD::FP_TO_SINT, MVT::i16, MVT::f64, 2 },
735 { ISD::FP_TO_UINT, MVT::i16, MVT::f64, 2 },
736 { ISD::FP_TO_SINT, MVT::i32, MVT::f32, 2 },
737 { ISD::FP_TO_UINT, MVT::i32, MVT::f32, 2 },
738 { ISD::FP_TO_SINT, MVT::i32, MVT::f64, 2 },
739 { ISD::FP_TO_UINT, MVT::i32, MVT::f64, 2 },
740 { ISD::FP_TO_SINT, MVT::i64, MVT::f32, 10 },
741 { ISD::FP_TO_UINT, MVT::i64, MVT::f32, 10 },
742 { ISD::FP_TO_SINT, MVT::i64, MVT::f64, 10 },
743 { ISD::FP_TO_UINT, MVT::i64, MVT::f64, 10 }
744 };
745 if (SrcTy.isFloatingPoint() && ST->hasNEON()) {
746 if (const auto *Entry = ConvertCostTableLookup(NEONFloatConversionTbl, ISD,
747 DstTy.getSimpleVT(),
748 SrcTy.getSimpleVT()))
749 return AdjustCost(Entry->Cost);
750 }
751
752 // Scalar integer to float conversions.
753 static const TypeConversionCostTblEntry NEONIntegerConversionTbl[] = {
754 { ISD::SINT_TO_FP, MVT::f32, MVT::i1, 2 },
755 { ISD::UINT_TO_FP, MVT::f32, MVT::i1, 2 },
756 { ISD::SINT_TO_FP, MVT::f64, MVT::i1, 2 },
757 { ISD::UINT_TO_FP, MVT::f64, MVT::i1, 2 },
758 { ISD::SINT_TO_FP, MVT::f32, MVT::i8, 2 },
759 { ISD::UINT_TO_FP, MVT::f32, MVT::i8, 2 },
760 { ISD::SINT_TO_FP, MVT::f64, MVT::i8, 2 },
761 { ISD::UINT_TO_FP, MVT::f64, MVT::i8, 2 },
762 { ISD::SINT_TO_FP, MVT::f32, MVT::i16, 2 },
763 { ISD::UINT_TO_FP, MVT::f32, MVT::i16, 2 },
764 { ISD::SINT_TO_FP, MVT::f64, MVT::i16, 2 },
765 { ISD::UINT_TO_FP, MVT::f64, MVT::i16, 2 },
766 { ISD::SINT_TO_FP, MVT::f32, MVT::i32, 2 },
767 { ISD::UINT_TO_FP, MVT::f32, MVT::i32, 2 },
768 { ISD::SINT_TO_FP, MVT::f64, MVT::i32, 2 },
769 { ISD::UINT_TO_FP, MVT::f64, MVT::i32, 2 },
770 { ISD::SINT_TO_FP, MVT::f32, MVT::i64, 10 },
771 { ISD::UINT_TO_FP, MVT::f32, MVT::i64, 10 },
772 { ISD::SINT_TO_FP, MVT::f64, MVT::i64, 10 },
773 { ISD::UINT_TO_FP, MVT::f64, MVT::i64, 10 }
774 };
775
776 if (SrcTy.isInteger() && ST->hasNEON()) {
777 if (const auto *Entry = ConvertCostTableLookup(NEONIntegerConversionTbl,
778 ISD, DstTy.getSimpleVT(),
779 SrcTy.getSimpleVT()))
780 return AdjustCost(Entry->Cost);
781 }
782
783 // MVE extend costs, taken from codegen tests. i8->i16 or i16->i32 is one
784 // instruction, i8->i32 is two. i64 zexts are an VAND with a constant, sext
785 // are linearised so take more.
786 static const TypeConversionCostTblEntry MVEVectorConversionTbl[] = {
787 { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
788 { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
789 { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
790 { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
791 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i8, 10 },
792 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i8, 2 },
793 { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
794 { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
795 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i16, 10 },
796 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i16, 2 },
797 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 8 },
798 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 2 },
799 };
800
801 if (SrcTy.isVector() && ST->hasMVEIntegerOps()) {
802 if (const auto *Entry = ConvertCostTableLookup(MVEVectorConversionTbl,
803 ISD, DstTy.getSimpleVT(),
804 SrcTy.getSimpleVT()))
805 return Entry->Cost * ST->getMVEVectorCostFactor(CostKind);
806 }
807
808 if (ISD == ISD::FP_ROUND || ISD == ISD::FP_EXTEND) {
809 // As general rule, fp converts that were not matched above are scalarized
810 // and cost 1 vcvt for each lane, so long as the instruction is available.
811 // If not it will become a series of function calls.
812 const InstructionCost CallCost =
813 getCallInstrCost(nullptr, Dst, {Src}, CostKind);
814 int Lanes = 1;
815 if (SrcTy.isFixedLengthVector())
816 Lanes = SrcTy.getVectorNumElements();
817
818 if (IsLegalFPType(SrcTy) && IsLegalFPType(DstTy))
819 return Lanes;
820 else
821 return Lanes * CallCost;
822 }
823
824 if (ISD == ISD::TRUNCATE && ST->hasMVEIntegerOps() &&
825 SrcTy.isFixedLengthVector()) {
826 // Treat a truncate with larger than legal source (128bits for MVE) as
827 // expensive, 2 instructions per lane.
828 if ((SrcTy.getScalarType() == MVT::i8 ||
829 SrcTy.getScalarType() == MVT::i16 ||
830 SrcTy.getScalarType() == MVT::i32) &&
831 SrcTy.getSizeInBits() > 128 &&
832 SrcTy.getSizeInBits() > DstTy.getSizeInBits())
833 return SrcTy.getVectorNumElements() * 2;
834 }
835
836 // Scalar integer conversion costs.
837 static const TypeConversionCostTblEntry ARMIntegerConversionTbl[] = {
838 // i16 -> i64 requires two dependent operations.
839 { ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 2 },
840
841 // Truncates on i64 are assumed to be free.
842 { ISD::TRUNCATE, MVT::i32, MVT::i64, 0 },
843 { ISD::TRUNCATE, MVT::i16, MVT::i64, 0 },
844 { ISD::TRUNCATE, MVT::i8, MVT::i64, 0 },
845 { ISD::TRUNCATE, MVT::i1, MVT::i64, 0 }
846 };
847
848 if (SrcTy.isInteger()) {
849 if (const auto *Entry = ConvertCostTableLookup(ARMIntegerConversionTbl, ISD,
850 DstTy.getSimpleVT(),
851 SrcTy.getSimpleVT()))
852 return AdjustCost(Entry->Cost);
853 }
854
855 int BaseCost = ST->hasMVEIntegerOps() && Src->isVectorTy()
856 ? ST->getMVEVectorCostFactor(CostKind)
857 : 1;
858 return AdjustCost(
859 BaseCost * BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
860}
861
863 unsigned Opcode, Type *ValTy, TTI::TargetCostKind CostKind, unsigned Index,
864 const Value *Op0, const Value *Op1, TTI::VectorInstrContext VIC) const {
865 // Penalize inserting into an D-subregister. We end up with a three times
866 // lower estimated throughput on swift.
867 if (ST->hasSlowLoadDSubregister() && Opcode == Instruction::InsertElement &&
868 ValTy->isVectorTy() && ValTy->getScalarSizeInBits() <= 32)
869 return 3;
870
871 if (ST->hasNEON() && (Opcode == Instruction::InsertElement ||
872 Opcode == Instruction::ExtractElement)) {
873 // Cross-class copies are expensive on many microarchitectures,
874 // so assume they are expensive by default.
875 if (cast<VectorType>(ValTy)->getElementType()->isIntegerTy())
876 return 3;
877
878 // Even if it's not a cross class copy, this likely leads to mixing
879 // of NEON and VFP code and should be therefore penalized.
880 if (ValTy->isVectorTy() &&
881 ValTy->getScalarSizeInBits() <= 32)
882 return std::max<InstructionCost>(
883 BaseT::getVectorInstrCost(Opcode, ValTy, CostKind, Index, Op0, Op1,
884 VIC),
885 2U);
886 }
887
888 if (ST->hasMVEIntegerOps() && (Opcode == Instruction::InsertElement ||
889 Opcode == Instruction::ExtractElement)) {
890 // Integer cross-lane moves are more expensive than float, which can
891 // sometimes just be vmovs. Integer involve being passes to GPR registers,
892 // causing more of a delay.
893 std::pair<InstructionCost, MVT> LT =
895 return LT.first * (ValTy->getScalarType()->isIntegerTy() ? 4 : 1);
896 }
897
898 return BaseT::getVectorInstrCost(Opcode, ValTy, CostKind, Index, Op0, Op1,
899 VIC);
900}
901
903 unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred,
905 TTI::OperandValueInfo Op2Info, const Instruction *I) const {
906 int ISD = TLI->InstructionOpcodeToISD(Opcode);
907
908 // Thumb scalar code size cost for select.
909 if (CostKind == TTI::TCK_CodeSize && ISD == ISD::SELECT &&
910 ST->isThumb() && !ValTy->isVectorTy()) {
911 // Assume expensive structs.
912 if (TLI->getValueType(DL, ValTy, true) == MVT::Other)
913 return TTI::TCC_Expensive;
914
915 // Select costs can vary because they:
916 // - may require one or more conditional mov (including an IT),
917 // - can't operate directly on immediates,
918 // - require live flags, which we can't copy around easily.
920
921 // Possible IT instruction for Thumb2, or more for Thumb1.
922 ++Cost;
923
924 // i1 values may need rematerialising by using mov immediates and/or
925 // flag setting instructions.
926 if (ValTy->isIntegerTy(1))
927 ++Cost;
928
929 return Cost;
930 }
931
932 // If this is a vector min/max/abs, use the cost of that intrinsic directly
933 // instead. Hopefully when min/max intrinsics are more prevalent this code
934 // will not be needed.
935 const Instruction *Sel = I;
936 if ((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) && Sel &&
937 Sel->hasOneUse())
938 Sel = Sel->user_back();
939 if (Sel && ValTy->isVectorTy() &&
940 (ValTy->isIntOrIntVectorTy() || ValTy->isFPOrFPVectorTy())) {
941 const Value *LHS, *RHS;
942 SelectPatternFlavor SPF = matchSelectPattern(Sel, LHS, RHS).Flavor;
943 unsigned IID = 0;
944 switch (SPF) {
945 case SPF_ABS:
946 IID = Intrinsic::abs;
947 break;
948 case SPF_SMIN:
949 IID = Intrinsic::smin;
950 break;
951 case SPF_SMAX:
952 IID = Intrinsic::smax;
953 break;
954 case SPF_UMIN:
955 IID = Intrinsic::umin;
956 break;
957 case SPF_UMAX:
958 IID = Intrinsic::umax;
959 break;
960 case SPF_FMINNUM:
961 IID = Intrinsic::minnum;
962 break;
963 case SPF_FMAXNUM:
964 IID = Intrinsic::maxnum;
965 break;
966 default:
967 break;
968 }
969 if (IID) {
970 // The ICmp is free, the select gets the cost of the min/max/etc
971 if (Sel != I)
972 return 0;
973 IntrinsicCostAttributes CostAttrs(IID, ValTy, {ValTy, ValTy});
974 return getIntrinsicInstrCost(CostAttrs, CostKind);
975 }
976 }
977
978 // On NEON a vector select gets lowered to vbsl.
979 if (ST->hasNEON() && ValTy->isVectorTy() && ISD == ISD::SELECT && CondTy) {
980 // Lowering of some vector selects is currently far from perfect.
981 static const TypeConversionCostTblEntry NEONVectorSelectTbl[] = {
982 { ISD::SELECT, MVT::v4i1, MVT::v4i64, 4*4 + 1*2 + 1 },
983 { ISD::SELECT, MVT::v8i1, MVT::v8i64, 50 },
984 { ISD::SELECT, MVT::v16i1, MVT::v16i64, 100 }
985 };
986
987 EVT SelCondTy = TLI->getValueType(DL, CondTy);
988 EVT SelValTy = TLI->getValueType(DL, ValTy);
989 if (SelCondTy.isSimple() && SelValTy.isSimple()) {
990 if (const auto *Entry = ConvertCostTableLookup(NEONVectorSelectTbl, ISD,
991 SelCondTy.getSimpleVT(),
992 SelValTy.getSimpleVT()))
993 return Entry->Cost;
994 }
995
996 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(ValTy);
997 return LT.first;
998 }
999
1000 if (ST->hasMVEIntegerOps() && ValTy->isVectorTy() &&
1001 (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
1002 cast<FixedVectorType>(ValTy)->getNumElements() > 1) {
1003 FixedVectorType *VecValTy = cast<FixedVectorType>(ValTy);
1005 if (!VecCondTy)
1007
1008 // If we don't have mve.fp any fp operations will need to be scalarized.
1009 if (Opcode == Instruction::FCmp && !ST->hasMVEFloatOps()) {
1010 // One scalaization insert, one scalarization extract and the cost of the
1011 // fcmps.
1012 return BaseT::getScalarizationOverhead(VecValTy, /*Insert*/ false,
1013 /*Extract*/ true, CostKind) +
1014 BaseT::getScalarizationOverhead(VecCondTy, /*Insert*/ true,
1015 /*Extract*/ false, CostKind) +
1016 VecValTy->getNumElements() *
1017 getCmpSelInstrCost(Opcode, ValTy->getScalarType(),
1018 VecCondTy->getScalarType(), VecPred,
1019 CostKind, Op1Info, Op2Info, I);
1020 }
1021
1022 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(ValTy);
1023 int BaseCost = ST->getMVEVectorCostFactor(CostKind);
1024 // There are two types - the input that specifies the type of the compare
1025 // and the output vXi1 type. Because we don't know how the output will be
1026 // split, we may need an expensive shuffle to get two in sync. This has the
1027 // effect of making larger than legal compares (v8i32 for example)
1028 // expensive.
1029 if (LT.second.isVector() && LT.second.getVectorNumElements() > 2) {
1030 if (LT.first > 1)
1031 return LT.first * BaseCost +
1032 BaseT::getScalarizationOverhead(VecCondTy, /*Insert*/ true,
1033 /*Extract*/ false, CostKind);
1034 return BaseCost;
1035 }
1036 }
1037
1038 // Default to cheap (throughput/size of 1 instruction) but adjust throughput
1039 // for "multiple beats" potentially needed by MVE instructions.
1040 int BaseCost = 1;
1041 if (ST->hasMVEIntegerOps() && ValTy->isVectorTy())
1042 BaseCost = ST->getMVEVectorCostFactor(CostKind);
1043
1044 return BaseCost * BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred,
1045 CostKind, Op1Info, Op2Info, I);
1046}
1047
1050 const SCEV *Ptr,
1051 TTI::TargetCostKind CostKind) const {
1052 // Address computations in vectorized code with non-consecutive addresses will
1053 // likely result in more instructions compared to scalar code where the
1054 // computation can more often be merged into the index mode. The resulting
1055 // extra micro-ops can significantly decrease throughput.
1056 unsigned NumVectorInstToHideOverhead = 10;
1057 int MaxMergeDistance = 64;
1058
1059 if (ST->hasNEON()) {
1060 if (PtrTy->isVectorTy() && SE &&
1061 !BaseT::isConstantStridedAccessLessThan(SE, Ptr, MaxMergeDistance + 1))
1062 return NumVectorInstToHideOverhead;
1063
1064 // In many cases the address computation is not merged into the instruction
1065 // addressing mode.
1066 return 1;
1067 }
1068 return BaseT::getAddressComputationCost(PtrTy, SE, Ptr, CostKind);
1069}
1070
1073 // If a VCTP is part of a chain, it's already profitable and shouldn't be
1074 // optimized, else LSR may block tail-predication.
1075 switch (II->getIntrinsicID()) {
1076 case Intrinsic::arm_mve_vctp8:
1077 case Intrinsic::arm_mve_vctp16:
1078 case Intrinsic::arm_mve_vctp32:
1079 case Intrinsic::arm_mve_vctp64:
1080 return true;
1081 default:
1082 break;
1083 }
1084 }
1085 return false;
1086}
1087
1089 unsigned /*AddressSpace*/,
1090 TTI::MaskKind /*MaskKind*/) const {
1091 if (!ST->getCLOpts().maskedldst || !ST->hasMVEIntegerOps())
1092 return false;
1093
1094 if (auto *VecTy = dyn_cast<FixedVectorType>(DataTy)) {
1095 // Don't support v2i1 yet.
1096 if (VecTy->getNumElements() == 2)
1097 return false;
1098
1099 // We don't support extending fp types.
1100 unsigned VecWidth = DataTy->getPrimitiveSizeInBits();
1101 if (VecWidth != 128 && VecTy->getElementType()->isFloatingPointTy())
1102 return false;
1103 }
1104
1105 unsigned EltWidth = DataTy->getScalarSizeInBits();
1106 return (EltWidth == 32 && Alignment >= 4) ||
1107 (EltWidth == 16 && Alignment >= 2) || (EltWidth == 8);
1108}
1109
1110bool ARMTTIImpl::isLegalMaskedGather(Type *Ty, Align Alignment) const {
1111 if (!ST->getCLOpts().maskedgatscat || !ST->hasMVEIntegerOps())
1112 return false;
1113
1114 unsigned EltWidth = Ty->getScalarSizeInBits();
1115 return ((EltWidth == 32 && Alignment >= 4) ||
1116 (EltWidth == 16 && Alignment >= 2) || EltWidth == 8);
1117}
1118
1119/// Given a memcpy/memset/memmove instruction, return the number of memory
1120/// operations performed, via querying findOptimalMemOpLowering. Returns -1 if a
1121/// call is used.
1123 MemOp MOp;
1124 unsigned DstAddrSpace = ~0u;
1125 unsigned SrcAddrSpace = ~0u;
1126 const Function *F = I->getParent()->getParent();
1127
1128 if (const auto *MC = dyn_cast<MemTransferInst>(I)) {
1129 ConstantInt *C = dyn_cast<ConstantInt>(MC->getLength());
1130 // If 'size' is not a constant, a library call will be generated.
1131 if (!C)
1132 return -1;
1133
1134 const unsigned Size = C->getValue().getZExtValue();
1135 const Align DstAlign = MC->getDestAlign().valueOrOne();
1136 const Align SrcAlign = MC->getSourceAlign().valueOrOne();
1137
1138 // Use the most restrictive of memset, memcpy, memmove.
1139 MOp = MemOp::Move(Size, /*DstAlignCanChange*/ false, DstAlign, SrcAlign,
1140 /*IsVolatile*/ false);
1141 DstAddrSpace = MC->getDestAddressSpace();
1142 SrcAddrSpace = MC->getSourceAddressSpace();
1143 }
1144 else if (const auto *MS = dyn_cast<MemSetInst>(I)) {
1145 ConstantInt *C = dyn_cast<ConstantInt>(MS->getLength());
1146 // If 'size' is not a constant, a library call will be generated.
1147 if (!C)
1148 return -1;
1149
1150 const unsigned Size = C->getValue().getZExtValue();
1151 const Align DstAlign = MS->getDestAlign().valueOrOne();
1152
1153 MOp = MemOp::Set(Size, /*DstAlignCanChange*/ false, DstAlign,
1154 /*IsZeroMemset*/ false, /*IsVolatile*/ false);
1155 DstAddrSpace = MS->getDestAddressSpace();
1156 }
1157 else
1158 llvm_unreachable("Expected a memcpy/move or memset!");
1159
1160 unsigned Limit, Factor = 2;
1161 switch(I->getIntrinsicID()) {
1162 case Intrinsic::memcpy:
1163 Limit = TLI->getMaxStoresPerMemcpy(F->hasMinSize());
1164 break;
1165 case Intrinsic::memmove:
1166 Limit = TLI->getMaxStoresPerMemmove(F->hasMinSize());
1167 break;
1168 case Intrinsic::memset:
1169 Limit = TLI->getMaxStoresPerMemset(F->hasMinSize());
1170 Factor = 1;
1171 break;
1172 default:
1173 llvm_unreachable("Expected a memcpy/move or memset!");
1174 }
1175
1176 // MemOps will be poplulated with a list of data types that needs to be
1177 // loaded and stored. That's why we multiply the number of elements by 2 to
1178 // get the cost for this memcpy.
1179 std::vector<EVT> MemOps;
1180 LLVMContext &C = F->getContext();
1181 if (getTLI()->findOptimalMemOpLowering(C, MemOps, Limit, MOp, DstAddrSpace,
1182 SrcAddrSpace, F->getAttributes(),
1183 nullptr))
1184 return MemOps.size() * Factor;
1185
1186 // If we can't find an optimal memop lowering, return the default cost
1187 return -1;
1188}
1189
1192
1193 // To model the cost of a library call, we assume 1 for the call, and
1194 // 3 for the argument setup.
1195 if (NumOps == -1)
1196 return 4;
1197 return NumOps;
1198}
1199
1201 TTI::ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy,
1202 TTI::TargetCostKind CostKind, ArrayRef<int> Mask, int Index,
1203 VectorType *SubTp, ArrayRef<const Value *> Args, const Instruction *CtxI,
1204 TTI::VectorInstrContext VIC) const {
1205 assert((Mask.empty() || DstTy->isScalableTy() ||
1206 Mask.size() == DstTy->getElementCount().getKnownMinValue()) &&
1207 "Expected the Mask to match the return size if given");
1208 assert(SrcTy->getScalarType() == DstTy->getScalarType() &&
1209 "Expected the same scalar types");
1210
1211 Kind = improveShuffleKindFromMask(Kind, Mask, SrcTy, Index, SubTp);
1212 // Treat extractsubvector as single op permutation.
1213 bool IsExtractSubvector = Kind == TTI::SK_ExtractSubvector;
1214 if (IsExtractSubvector)
1216 if (ST->hasNEON()) {
1217 if (Kind == TTI::SK_Broadcast) {
1218 static const CostTblEntry NEONDupTbl[] = {
1219 // VDUP handles these cases.
1220 {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
1221 {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
1222 {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
1223 {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
1224 {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1},
1225 {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1},
1226
1227 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
1228 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
1229 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
1230 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1}};
1231
1232 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(SrcTy);
1233 if (const auto *Entry =
1234 CostTableLookup(NEONDupTbl, ISD::VECTOR_SHUFFLE, LT.second))
1235 return LT.first * Entry->Cost;
1236 }
1237 if (Kind == TTI::SK_Reverse) {
1238 static const CostTblEntry NEONShuffleTbl[] = {
1239 // Reverse shuffle cost one instruction if we are shuffling within a
1240 // double word (vrev) or two if we shuffle a quad word (vrev, vext).
1241 {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
1242 {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
1243 {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
1244 {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
1245 {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1},
1246 {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1},
1247
1248 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
1249 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
1250 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 2},
1251 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 2}};
1252
1253 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(SrcTy);
1254 if (const auto *Entry =
1255 CostTableLookup(NEONShuffleTbl, ISD::VECTOR_SHUFFLE, LT.second))
1256 return LT.first * Entry->Cost;
1257 }
1258 if (Kind == TTI::SK_Select) {
1259 static const CostTblEntry NEONSelShuffleTbl[] = {
1260 // Select shuffle cost table for ARM. Cost is the number of
1261 // instructions
1262 // required to create the shuffled vector.
1263
1264 {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
1265 {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
1266 {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
1267 {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
1268
1269 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
1270 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
1271 {ISD::VECTOR_SHUFFLE, MVT::v4i16, 2},
1272
1273 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 16},
1274
1275 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 32}};
1276
1277 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(SrcTy);
1278 if (const auto *Entry = CostTableLookup(NEONSelShuffleTbl,
1279 ISD::VECTOR_SHUFFLE, LT.second))
1280 return LT.first * Entry->Cost;
1281 }
1282
1283 // Check for other shuffles that are not SK_ kinds but we have native
1284 // instructions for, for example REV.
1285 if (!Mask.empty()) {
1286 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(SrcTy);
1287 unsigned Unused;
1288 if (LT.second.isVector() &&
1289 Mask.size() <= LT.second.getVectorNumElements() &&
1290 (isVREVMask(Mask, LT.second, 16) || isVREVMask(Mask, LT.second, 32) ||
1291 isVREVMask(Mask, LT.second, 64) ||
1292 isVTRNMask(Mask, LT.second, Unused) ||
1293 isVTRN_v_undef_Mask(Mask, LT.second, Unused) ||
1294 isVZIPMask(Mask, LT.second, Unused) ||
1295 isVZIP_v_undef_Mask(Mask, LT.second, Unused) ||
1296 isVUZPMask(Mask, LT.second, Unused) ||
1297 isVUZP_v_undef_Mask(Mask, LT.second, Unused)))
1298 return LT.first;
1299 }
1300 }
1301 if (ST->hasMVEIntegerOps()) {
1302 if (Kind == TTI::SK_Broadcast) {
1303 static const CostTblEntry MVEDupTbl[] = {
1304 // VDUP handles these cases.
1305 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
1306 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
1307 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1},
1308 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
1309 {ISD::VECTOR_SHUFFLE, MVT::v8f16, 1}};
1310
1311 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(SrcTy);
1312 if (const auto *Entry = CostTableLookup(MVEDupTbl, ISD::VECTOR_SHUFFLE,
1313 LT.second))
1314 return LT.first * Entry->Cost * ST->getMVEVectorCostFactor(CostKind);
1315 }
1316
1317 if (!Mask.empty()) {
1318 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(SrcTy);
1319 // Check for LD2/LD4 instructions, which are represented in llvm IR as
1320 // deinterleaving-shuffle(load). The shuffle cost could potentially be
1321 // free, but we model it with a cost of LT.first so that LD2/LD4 have a
1322 // higher cost than just the load.
1323 if (Args.size() >= 1 && isa<LoadInst>(Args[0]) &&
1324 (LT.second.getScalarSizeInBits() == 8 ||
1325 LT.second.getScalarSizeInBits() == 16 ||
1326 LT.second.getScalarSizeInBits() == 32) &&
1327 LT.second.getSizeInBits() == 128 &&
1328 ((TLI->getMaxSupportedInterleaveFactor() >= 2 &&
1330 (TLI->getMaxSupportedInterleaveFactor() == 4 &&
1332 return ST->getMVEVectorCostFactor(CostKind) *
1333 std::max<InstructionCost>(1, LT.first / 4);
1334
1335 // Check for ST2/ST4 instructions, which are represented in llvm IR as
1336 // store(interleaving-shuffle). The shuffle cost could potentially be
1337 // free, but we model it with a cost of LT.first so that ST2/ST4 have a
1338 // higher cost than just the store.
1339 if (CtxI && CtxI->hasOneUse() && isa<StoreInst>(*CtxI->user_begin()) &&
1340 (LT.second.getScalarSizeInBits() == 8 ||
1341 LT.second.getScalarSizeInBits() == 16 ||
1342 LT.second.getScalarSizeInBits() == 32) &&
1343 LT.second.getSizeInBits() == 128 &&
1344 ((TLI->getMaxSupportedInterleaveFactor() >= 2 &&
1346 Mask, 2, SrcTy->getElementCount().getKnownMinValue() * 2)) ||
1347 (TLI->getMaxSupportedInterleaveFactor() == 4 &&
1349 Mask, 4, SrcTy->getElementCount().getKnownMinValue() * 2))))
1350 return ST->getMVEVectorCostFactor(CostKind) * LT.first;
1351
1352 if (LT.second.isVector() &&
1353 Mask.size() <= LT.second.getVectorNumElements() &&
1354 (isVREVMask(Mask, LT.second, 16) || isVREVMask(Mask, LT.second, 32) ||
1355 isVREVMask(Mask, LT.second, 64)))
1356 return ST->getMVEVectorCostFactor(CostKind) * LT.first;
1357 }
1358 }
1359
1360 // Restore optimal kind.
1361 if (IsExtractSubvector)
1363 int BaseCost = ST->hasMVEIntegerOps() && SrcTy->isVectorTy()
1364 ? ST->getMVEVectorCostFactor(CostKind)
1365 : 1;
1366 return BaseCost * BaseT::getShuffleCost(Kind, DstTy, SrcTy, CostKind, Mask,
1367 Index, SubTp);
1368}
1369
1371 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
1373 ArrayRef<const Value *> Args, const Instruction *CtxI,
1374 const TargetLibraryInfo *TLibInfo, ArrayRef<const Value *> Scalars) const {
1375 int ISDOpcode = TLI->InstructionOpcodeToISD(Opcode);
1376 if (ST->isThumb() && CostKind == TTI::TCK_CodeSize && Ty->isIntegerTy(1)) {
1377 // Make operations on i1 relatively expensive as this often involves
1378 // combining predicates. AND and XOR should be easier to handle with IT
1379 // blocks.
1380 switch (ISDOpcode) {
1381 default:
1382 break;
1383 case ISD::AND:
1384 case ISD::XOR:
1385 return 2;
1386 case ISD::OR:
1387 return 3;
1388 }
1389 }
1390
1391 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Ty);
1392
1393 if (ST->hasNEON()) {
1394 const unsigned FunctionCallDivCost = 20;
1395 const unsigned ReciprocalDivCost = 10;
1396 static const CostTblEntry CostTbl[] = {
1397 // Division.
1398 // These costs are somewhat random. Choose a cost of 20 to indicate that
1399 // vectorizing devision (added function call) is going to be very expensive.
1400 // Double registers types.
1401 { ISD::SDIV, MVT::v1i64, 1 * FunctionCallDivCost},
1402 { ISD::UDIV, MVT::v1i64, 1 * FunctionCallDivCost},
1403 { ISD::SREM, MVT::v1i64, 1 * FunctionCallDivCost},
1404 { ISD::UREM, MVT::v1i64, 1 * FunctionCallDivCost},
1405 { ISD::SDIV, MVT::v2i32, 2 * FunctionCallDivCost},
1406 { ISD::UDIV, MVT::v2i32, 2 * FunctionCallDivCost},
1407 { ISD::SREM, MVT::v2i32, 2 * FunctionCallDivCost},
1408 { ISD::UREM, MVT::v2i32, 2 * FunctionCallDivCost},
1409 { ISD::SDIV, MVT::v4i16, ReciprocalDivCost},
1410 { ISD::UDIV, MVT::v4i16, ReciprocalDivCost},
1411 { ISD::SREM, MVT::v4i16, 4 * FunctionCallDivCost},
1412 { ISD::UREM, MVT::v4i16, 4 * FunctionCallDivCost},
1413 { ISD::SDIV, MVT::v8i8, ReciprocalDivCost},
1414 { ISD::UDIV, MVT::v8i8, ReciprocalDivCost},
1415 { ISD::SREM, MVT::v8i8, 8 * FunctionCallDivCost},
1416 { ISD::UREM, MVT::v8i8, 8 * FunctionCallDivCost},
1417 // Quad register types.
1418 { ISD::SDIV, MVT::v2i64, 2 * FunctionCallDivCost},
1419 { ISD::UDIV, MVT::v2i64, 2 * FunctionCallDivCost},
1420 { ISD::SREM, MVT::v2i64, 2 * FunctionCallDivCost},
1421 { ISD::UREM, MVT::v2i64, 2 * FunctionCallDivCost},
1422 { ISD::SDIV, MVT::v4i32, 4 * FunctionCallDivCost},
1423 { ISD::UDIV, MVT::v4i32, 4 * FunctionCallDivCost},
1424 { ISD::SREM, MVT::v4i32, 4 * FunctionCallDivCost},
1425 { ISD::UREM, MVT::v4i32, 4 * FunctionCallDivCost},
1426 { ISD::SDIV, MVT::v8i16, 8 * FunctionCallDivCost},
1427 { ISD::UDIV, MVT::v8i16, 8 * FunctionCallDivCost},
1428 { ISD::SREM, MVT::v8i16, 8 * FunctionCallDivCost},
1429 { ISD::UREM, MVT::v8i16, 8 * FunctionCallDivCost},
1430 { ISD::SDIV, MVT::v16i8, 16 * FunctionCallDivCost},
1431 { ISD::UDIV, MVT::v16i8, 16 * FunctionCallDivCost},
1432 { ISD::SREM, MVT::v16i8, 16 * FunctionCallDivCost},
1433 { ISD::UREM, MVT::v16i8, 16 * FunctionCallDivCost},
1434 // Multiplication.
1435 };
1436
1437 if (const auto *Entry = CostTableLookup(CostTbl, ISDOpcode, LT.second))
1438 return LT.first * Entry->Cost;
1439
1441 Opcode, Ty, CostKind, Op1Info, Op2Info);
1442
1443 // This is somewhat of a hack. The problem that we are facing is that SROA
1444 // creates a sequence of shift, and, or instructions to construct values.
1445 // These sequences are recognized by the ISel and have zero-cost. Not so for
1446 // the vectorized code. Because we have support for v2i64 but not i64 those
1447 // sequences look particularly beneficial to vectorize.
1448 // To work around this we increase the cost of v2i64 operations to make them
1449 // seem less beneficial.
1450 if (LT.second == MVT::v2i64 && Op2Info.isUniform() && Op2Info.isConstant())
1451 Cost += 4;
1452
1453 return Cost;
1454 }
1455
1456 // If this operation is a shift on arm/thumb2, it might well be folded into
1457 // the following instruction, hence having a cost of 0.
1458 auto LooksLikeAFreeShift = [&]() {
1459 if (ST->isThumb1Only() || Ty->isVectorTy())
1460 return false;
1461
1462 if (!CtxI || !CtxI->hasOneUse() || !CtxI->isShift())
1463 return false;
1464 if (!Op2Info.isUniform() || !Op2Info.isConstant())
1465 return false;
1466
1467 // Folded into a ADC/ADD/AND/BIC/CMP/EOR/MVN/ORR/ORN/RSB/SBC/SUB
1468 switch (CtxI->user_back()->getOpcode()) {
1469 case Instruction::Add:
1470 case Instruction::Sub:
1471 case Instruction::And:
1472 case Instruction::Xor:
1473 case Instruction::Or:
1474 case Instruction::ICmp:
1475 return true;
1476 default:
1477 return false;
1478 }
1479 };
1480 if (LooksLikeAFreeShift())
1481 return 0;
1482
1483 // When targets have both DSP and MVE we find that the
1484 // the compiler will attempt to vectorize as well as using
1485 // scalar (S/U)MLAL operations. This is in cases where we have
1486 // the pattern ext(mul(ext(i16), ext(i16))) we find
1487 // that codegen performs better when only using (S/U)MLAL scalar
1488 // ops instead of trying to mix vector ops with (S/U)MLAL ops. We therefore
1489 // check if a mul instruction is used in a (U/S)MLAL pattern.
1490 auto MulInDSPMLALPattern = [&](const Instruction *I, unsigned Opcode,
1491 Type *Ty) -> bool {
1492 if (!ST->hasDSP())
1493 return false;
1494
1495 if (!I)
1496 return false;
1497
1498 if (Opcode != Instruction::Mul)
1499 return false;
1500
1501 if (Ty->isVectorTy())
1502 return false;
1503
1504 auto ValueOpcodesEqual = [](const Value *LHS, const Value *RHS) -> bool {
1505 return cast<Instruction>(LHS)->getOpcode() ==
1506 cast<Instruction>(RHS)->getOpcode();
1507 };
1508 auto IsExtInst = [](const Value *V) -> bool {
1509 return isa<ZExtInst>(V) || isa<SExtInst>(V);
1510 };
1511 auto IsExtensionFromHalf = [](const Value *V) -> bool {
1512 return cast<Instruction>(V)->getOperand(0)->getType()->isIntegerTy(16);
1513 };
1514
1515 // We check the arguments of the instruction to see if they're extends
1516 auto *BinOp = dyn_cast<BinaryOperator>(I);
1517 if (!BinOp)
1518 return false;
1519 Value *Op0 = BinOp->getOperand(0);
1520 Value *Op1 = BinOp->getOperand(1);
1521 if (IsExtInst(Op0) && IsExtInst(Op1) && ValueOpcodesEqual(Op0, Op1)) {
1522 // We're interested in an ext of an i16
1523 if (!I->getType()->isIntegerTy(32) || !IsExtensionFromHalf(Op0) ||
1524 !IsExtensionFromHalf(Op1))
1525 return false;
1526 // We need to check if this result will be further extended to i64
1527 // and that all these uses are SExt
1528 for (auto *U : I->users())
1529 if (!IsExtInst(U))
1530 return false;
1531 return true;
1532 }
1533
1534 return false;
1535 };
1536
1537 if (MulInDSPMLALPattern(CtxI, Opcode, Ty))
1538 return 0;
1539
1540 // Default to cheap (throughput/size of 1 instruction) but adjust throughput
1541 // for "multiple beats" potentially needed by MVE instructions.
1542 int BaseCost = 1;
1543 if (ST->hasMVEIntegerOps() && Ty->isVectorTy())
1544 BaseCost = ST->getMVEVectorCostFactor(CostKind);
1545
1546 // The rest of this mostly follows what is done in
1547 // BaseT::getArithmeticInstrCost, without treating floats as more expensive
1548 // that scalars or increasing the costs for custom operations. The results is
1549 // also multiplied by the MVEVectorCostFactor where appropriate.
1550 if (TLI->isOperationLegalOrCustomOrPromote(ISDOpcode, LT.second))
1551 return LT.first * BaseCost;
1552
1553 // Else this is expand, assume that we need to scalarize this op.
1554 if (auto *VTy = dyn_cast<FixedVectorType>(Ty)) {
1555 unsigned Num = VTy->getNumElements();
1557 getArithmeticInstrCost(Opcode, Ty->getScalarType(), CostKind);
1558 // Return the cost of multiple scalar invocation plus the cost of
1559 // inserting and extracting the values.
1560 SmallVector<Type *> Tys(Args.size(), Ty);
1561 return BaseT::getScalarizationOverhead(VTy, Args, Tys, CostKind) +
1562 Num * Cost;
1563 }
1564
1565 return BaseCost;
1566}
1567
1569 Align Alignment,
1570 unsigned AddressSpace,
1571 TTI::TargetCostKind CostKind,
1572 TTI::OperandValueInfo OpInfo,
1573 const Instruction *I) const {
1574 // FIXME: Load latency isn't handled here
1575 if (Opcode == Instruction::Load && CostKind == TTI::TCK_Latency)
1576 return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
1577 CostKind, OpInfo, I);
1578
1579 // TODO: Handle other cost kinds.
1580 if (CostKind != TTI::TCK_RecipThroughput)
1581 return 1;
1582
1583 // Type legalization can't handle structs
1584 if (TLI->getValueType(DL, Src, true) == MVT::Other)
1585 return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
1586 CostKind);
1587
1588 if (ST->hasNEON() && Src->isVectorTy() && Alignment != Align(16) &&
1589 cast<VectorType>(Src)->getElementType()->isDoubleTy()) {
1590 // Unaligned loads/stores are extremely inefficient.
1591 // We need 4 uops for vst.1/vld.1 vs 1uop for vldr/vstr.
1592 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Src);
1593 return LT.first * 4;
1594 }
1595
1596 // MVE can optimize a fpext(load(4xhalf)) using an extending integer load.
1597 // Same for stores.
1598 if (ST->hasMVEFloatOps() && isa<FixedVectorType>(Src) && I &&
1599 ((Opcode == Instruction::Load && I->hasOneUse() &&
1600 isa<FPExtInst>(*I->user_begin())) ||
1601 (Opcode == Instruction::Store && isa<FPTruncInst>(I->getOperand(0))))) {
1603 Type *DstTy =
1604 Opcode == Instruction::Load
1605 ? (*I->user_begin())->getType()
1606 : cast<Instruction>(I->getOperand(0))->getOperand(0)->getType();
1607 if (SrcVTy->getNumElements() == 4 && SrcVTy->getScalarType()->isHalfTy() &&
1608 DstTy->getScalarType()->isFloatTy())
1609 return ST->getMVEVectorCostFactor(CostKind);
1610 }
1611
1612 int BaseCost = ST->hasMVEIntegerOps() && Src->isVectorTy()
1613 ? ST->getMVEVectorCostFactor(CostKind)
1614 : 1;
1615 return BaseCost * BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
1616 CostKind, OpInfo, I);
1617}
1618
1621 TTI::TargetCostKind CostKind) const {
1622 switch (MICA.getID()) {
1623 case Intrinsic::masked_scatter:
1624 case Intrinsic::masked_gather:
1625 return getGatherScatterOpCost(MICA, CostKind);
1626 case Intrinsic::masked_load:
1627 case Intrinsic::masked_store:
1628 return getMaskedMemoryOpCost(MICA, CostKind);
1629 }
1630 return BaseT::getMemIntrinsicInstrCost(MICA, CostKind);
1631}
1632
1635 TTI::TargetCostKind CostKind) const {
1636 unsigned IID = MICA.getID();
1637 Type *Src = MICA.getDataType();
1638 Align Alignment = MICA.getAlignment();
1639 unsigned AddressSpace = MICA.getAddressSpace();
1640 if (ST->hasMVEIntegerOps()) {
1641 if (IID == Intrinsic::masked_load &&
1642 isLegalMaskedLoad(Src, Alignment, AddressSpace))
1643 return ST->getMVEVectorCostFactor(CostKind);
1644 if (IID == Intrinsic::masked_store &&
1645 isLegalMaskedStore(Src, Alignment, AddressSpace))
1646 return ST->getMVEVectorCostFactor(CostKind);
1647 }
1648 if (!isa<FixedVectorType>(Src))
1649 return BaseT::getMemIntrinsicInstrCost(MICA, CostKind);
1650 // Scalar cost, which is currently very high due to the efficiency of the
1651 // generated code.
1652 return cast<FixedVectorType>(Src)->getNumElements() * 8;
1653}
1654
1656 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
1657 Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
1658 bool UseMaskForCond, bool UseMaskForGaps) const {
1659 assert(Factor >= 2 && "Invalid interleave factor");
1660 assert(isa<VectorType>(VecTy) && "Expect a vector type");
1661
1662 // vldN/vstN doesn't support vector types of i64/f64 element.
1663 bool EltIs64Bits = DL.getTypeSizeInBits(VecTy->getScalarType()) == 64;
1664
1665 if (Factor <= TLI->getMaxSupportedInterleaveFactor() && !EltIs64Bits &&
1666 !UseMaskForCond && !UseMaskForGaps) {
1667 unsigned NumElts = cast<FixedVectorType>(VecTy)->getNumElements();
1668 auto *SubVecTy =
1669 FixedVectorType::get(VecTy->getScalarType(), NumElts / Factor);
1670
1671 // vldN/vstN only support legal vector types of size 64 or 128 in bits.
1672 // Accesses having vector types that are a multiple of 128 bits can be
1673 // matched to more than one vldN/vstN instruction.
1674 int BaseCost =
1675 ST->hasMVEIntegerOps() ? ST->getMVEVectorCostFactor(CostKind) : 1;
1676 if (NumElts % Factor == 0 &&
1677 TLI->isLegalInterleavedAccessType(Factor, SubVecTy, Alignment, DL))
1678 return Factor * BaseCost * TLI->getNumInterleavedAccesses(SubVecTy, DL);
1679
1680 // Some smaller than legal interleaved patterns are cheap as we can make
1681 // use of the vmovn or vrev patterns to interleave a standard load. This is
1682 // true for v4i8, v8i8 and v4i16 at least (but not for v4f16 as it is
1683 // promoted differently). The cost of 2 here is then a load and vrev or
1684 // vmovn.
1685 if (ST->hasMVEIntegerOps() && Factor == 2 && NumElts / Factor > 2 &&
1686 VecTy->isIntOrIntVectorTy() &&
1687 DL.getTypeSizeInBits(SubVecTy).getFixedValue() <= 64)
1688 return 2 * BaseCost;
1689 }
1690
1691 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
1692 Alignment, AddressSpace, CostKind,
1693 UseMaskForCond, UseMaskForGaps);
1694}
1695
1698 TTI::TargetCostKind CostKind) const {
1699
1700 Type *DataTy = MICA.getDataType();
1701 const Value *Ptr = MICA.getPointer();
1702 bool VariableMask = MICA.getVariableMask();
1703 Align Alignment = MICA.getAlignment();
1704 const Instruction *I = MICA.getInst();
1705
1706 using namespace PatternMatch;
1707 if (!ST->hasMVEIntegerOps() || !ST->getCLOpts().maskedgatscat)
1708 return BaseT::getMemIntrinsicInstrCost(MICA, CostKind);
1709
1710 assert(DataTy->isVectorTy() && "Can't do gather/scatters on scalar!");
1711 auto *VTy = cast<FixedVectorType>(DataTy);
1712
1713 // TODO: Splitting, once we do that.
1714
1715 unsigned NumElems = VTy->getNumElements();
1716 unsigned EltSize = VTy->getScalarSizeInBits();
1717 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(DataTy);
1718
1719 // For now, it is assumed that for the MVE gather instructions the loads are
1720 // all effectively serialised. This means the cost is the scalar cost
1721 // multiplied by the number of elements being loaded. This is possibly very
1722 // conservative, but even so we still end up vectorising loops because the
1723 // cost per iteration for many loops is lower than for scalar loops.
1724 InstructionCost VectorCost =
1725 NumElems * LT.first * ST->getMVEVectorCostFactor(CostKind);
1726 // The scalarization cost should be a lot higher. We use the number of vector
1727 // elements plus the scalarization overhead. If masking is required then a lot
1728 // of little blocks will be needed and potentially a scalarized p0 mask,
1729 // greatly increasing the cost.
1730 InstructionCost ScalarCost =
1731 NumElems * LT.first + (VariableMask ? NumElems * 5 : 0) +
1732 BaseT::getScalarizationOverhead(VTy, /*Insert*/ true, /*Extract*/ false,
1733 CostKind) +
1734 BaseT::getScalarizationOverhead(VTy, /*Insert*/ false, /*Extract*/ true,
1735 CostKind);
1736
1737 if (EltSize < 8 || Alignment < EltSize / 8)
1738 return ScalarCost;
1739
1740 unsigned ExtSize = EltSize;
1741 // Check whether there's a single user that asks for an extended type
1742 if (I != nullptr) {
1743 // Dependent of the caller of this function, a gather instruction will
1744 // either have opcode Instruction::Load or be a call to the masked_gather
1745 // intrinsic
1746 if ((I->getOpcode() == Instruction::Load ||
1748 I->hasOneUse()) {
1749 const User *Us = *I->users().begin();
1750 if (isa<ZExtInst>(Us) || isa<SExtInst>(Us)) {
1751 // only allow valid type combinations
1752 unsigned TypeSize =
1753 cast<Instruction>(Us)->getType()->getScalarSizeInBits();
1754 if (((TypeSize == 32 && (EltSize == 8 || EltSize == 16)) ||
1755 (TypeSize == 16 && EltSize == 8)) &&
1756 TypeSize * NumElems == 128) {
1757 ExtSize = TypeSize;
1758 }
1759 }
1760 }
1761 // Check whether the input data needs to be truncated
1762 TruncInst *T;
1763 if ((I->getOpcode() == Instruction::Store ||
1765 (T = dyn_cast<TruncInst>(I->getOperand(0)))) {
1766 // Only allow valid type combinations
1767 unsigned TypeSize = T->getOperand(0)->getType()->getScalarSizeInBits();
1768 if (((EltSize == 16 && TypeSize == 32) ||
1769 (EltSize == 8 && (TypeSize == 32 || TypeSize == 16))) &&
1770 TypeSize * NumElems == 128)
1771 ExtSize = TypeSize;
1772 }
1773 }
1774
1775 if (ExtSize * NumElems != 128 || NumElems < 4)
1776 return ScalarCost;
1777
1778 // Any (aligned) i32 gather will not need to be scalarised.
1779 if (ExtSize == 32)
1780 return VectorCost;
1781 // For smaller types, we need to ensure that the gep's inputs are correctly
1782 // extended from a small enough value. Other sizes (including i64) are
1783 // scalarized for now.
1784 if (ExtSize != 8 && ExtSize != 16)
1785 return ScalarCost;
1786
1787 if (const auto *BC = dyn_cast<BitCastInst>(Ptr))
1788 Ptr = BC->getOperand(0);
1789 if (const auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
1790 if (GEP->getNumOperands() != 2)
1791 return ScalarCost;
1792 unsigned Scale = DL.getTypeAllocSize(GEP->getResultElementType());
1793 // Scale needs to be correct (which is only relevant for i16s).
1794 if (Scale != 1 && Scale * 8 != ExtSize)
1795 return ScalarCost;
1796 // And we need to zext (not sext) the indexes from a small enough type.
1797 if (const auto *ZExt = dyn_cast<ZExtInst>(GEP->getOperand(1))) {
1798 if (ZExt->getOperand(0)->getType()->getScalarSizeInBits() <= ExtSize)
1799 return VectorCost;
1800 }
1801 return ScalarCost;
1802 }
1803 return ScalarCost;
1804}
1805
1808 std::optional<FastMathFlags> FMF,
1809 TTI::TargetCostKind CostKind) const {
1810
1811 EVT ValVT = TLI->getValueType(DL, ValTy);
1812 int ISD = TLI->InstructionOpcodeToISD(Opcode);
1813 unsigned EltSize = ValVT.getScalarSizeInBits();
1814
1815 // In general floating point reductions are a series of elementwise
1816 // operations, with free extracts on each step. These are either in-order or
1817 // treewise depending on whether that is allowed by the fast math flags.
1818 if ((ISD == ISD::FADD || ISD == ISD::FMUL) &&
1819 ((EltSize == 32 && ST->hasVFP2Base()) ||
1820 (EltSize == 64 && ST->hasFP64()) ||
1821 (EltSize == 16 && ST->hasFullFP16()))) {
1822 unsigned NumElts = cast<FixedVectorType>(ValTy)->getNumElements();
1823 unsigned VecLimit = ST->hasMVEFloatOps() ? 128 : (ST->hasNEON() ? 64 : -1);
1824 InstructionCost VecCost = 0;
1825 while (!TTI::requiresOrderedReduction(FMF) && isPowerOf2_32(NumElts) &&
1826 NumElts * EltSize > VecLimit) {
1827 Type *VecTy = FixedVectorType::get(ValTy->getElementType(), NumElts / 2);
1828 VecCost += getArithmeticInstrCost(Opcode, VecTy, CostKind);
1829 NumElts /= 2;
1830 }
1831
1832 // For fp16 we need to extract the upper lane elements. MVE can add a
1833 // VREV+FMIN/MAX to perform another vector step instead.
1834 InstructionCost ExtractCost = 0;
1835 if (!TTI::requiresOrderedReduction(FMF) && ST->hasMVEFloatOps() &&
1836 ValVT.getVectorElementType() == MVT::f16 && NumElts == 8) {
1837 VecCost += ST->getMVEVectorCostFactor(CostKind) * 2;
1838 NumElts /= 2;
1839 } else if (ValVT.getVectorElementType() == MVT::f16)
1840 ExtractCost = NumElts / 2;
1841
1842 return VecCost + ExtractCost +
1843 NumElts *
1844 getArithmeticInstrCost(Opcode, ValTy->getElementType(), CostKind);
1845 }
1846
1847 if ((ISD == ISD::AND || ISD == ISD::OR || ISD == ISD::XOR) &&
1848 (EltSize == 64 || EltSize == 32 || EltSize == 16 || EltSize == 8)) {
1849 unsigned NumElts = cast<FixedVectorType>(ValTy)->getNumElements();
1850 unsigned VecLimit =
1851 ST->hasMVEIntegerOps() ? 128 : (ST->hasNEON() ? 64 : -1);
1852 InstructionCost VecCost = 0;
1853 while (isPowerOf2_32(NumElts) && NumElts * EltSize > VecLimit) {
1854 Type *VecTy = FixedVectorType::get(ValTy->getElementType(), NumElts / 2);
1855 VecCost += getArithmeticInstrCost(Opcode, VecTy, CostKind);
1856 NumElts /= 2;
1857 }
1858 // For i16/i8, MVE will perform a VREV + VORR/VAND/VEOR for the 64bit vector
1859 // step.
1860 if (ST->hasMVEIntegerOps() && ValVT.getScalarSizeInBits() <= 16 &&
1861 NumElts * EltSize == 64) {
1862 Type *VecTy = FixedVectorType::get(ValTy->getElementType(), NumElts);
1863 VecCost += ST->getMVEVectorCostFactor(CostKind) +
1864 getArithmeticInstrCost(Opcode, VecTy, CostKind);
1865 NumElts /= 2;
1866 }
1867
1868 // From here we extract the elements and perform the and/or/xor.
1869 InstructionCost ExtractCost = NumElts;
1870 return VecCost + ExtractCost +
1871 (NumElts - 1) * getArithmeticInstrCost(
1872 Opcode, ValTy->getElementType(), CostKind);
1873 }
1874
1875 if (!ST->hasMVEIntegerOps() || !ValVT.isSimple() || ISD != ISD::ADD ||
1877 return BaseT::getArithmeticReductionCost(Opcode, ValTy, FMF, CostKind);
1878
1879 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(ValTy);
1880
1881 static const CostTblEntry CostTblAdd[]{
1882 {ISD::ADD, MVT::v16i8, 1},
1883 {ISD::ADD, MVT::v8i16, 1},
1884 {ISD::ADD, MVT::v4i32, 1},
1885 };
1886 if (const auto *Entry = CostTableLookup(CostTblAdd, ISD, LT.second))
1887 return Entry->Cost * ST->getMVEVectorCostFactor(CostKind) * LT.first;
1888
1889 return BaseT::getArithmeticReductionCost(Opcode, ValTy, FMF, CostKind);
1890}
1891
1893 unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *ValTy,
1894 std::optional<FastMathFlags> FMF, TTI::TargetCostKind CostKind) const {
1895 EVT ValVT = TLI->getValueType(DL, ValTy);
1896 EVT ResVT = TLI->getValueType(DL, ResTy);
1897
1898 int ISD = TLI->InstructionOpcodeToISD(Opcode);
1899
1900 switch (ISD) {
1901 case ISD::ADD:
1902 if (ST->hasMVEIntegerOps() && ValVT.isSimple() && ResVT.isSimple()) {
1903 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(ValTy);
1904
1905 // The legal cases are:
1906 // VADDV u/s 8/16/32
1907 // VADDLV u/s 32
1908 // Codegen currently cannot always handle larger than legal vectors very
1909 // well, especially for predicated reductions where the mask needs to be
1910 // split, so restrict to 128bit or smaller input types.
1911 unsigned RevVTSize = ResVT.getSizeInBits();
1912 if (ValVT.getSizeInBits() <= 128 &&
1913 ((LT.second == MVT::v16i8 && RevVTSize <= 32) ||
1914 (LT.second == MVT::v8i16 && RevVTSize <= 32) ||
1915 (LT.second == MVT::v4i32 && RevVTSize <= 64)))
1916 return ST->getMVEVectorCostFactor(CostKind) * LT.first;
1917 }
1918 break;
1919 default:
1920 break;
1921 }
1922 return BaseT::getExtendedReductionCost(Opcode, IsUnsigned, ResTy, ValTy, FMF,
1923 CostKind);
1924}
1925
1927ARMTTIImpl::getMulAccReductionCost(bool IsUnsigned, unsigned RedOpcode,
1928 Type *ResTy, VectorType *ValTy,
1929 TTI::TargetCostKind CostKind) const {
1930 if (RedOpcode != Instruction::Add)
1931 return InstructionCost::getInvalid(CostKind);
1932 EVT ValVT = TLI->getValueType(DL, ValTy);
1933 EVT ResVT = TLI->getValueType(DL, ResTy);
1934
1935 if (ST->hasMVEIntegerOps() && ValVT.isSimple() && ResVT.isSimple()) {
1936 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(ValTy);
1937
1938 // The legal cases are:
1939 // VMLAV u/s 8/16/32
1940 // VMLALV u/s 16/32
1941 // Codegen currently cannot always handle larger than legal vectors very
1942 // well, especially for predicated reductions where the mask needs to be
1943 // split, so restrict to 128bit or smaller input types.
1944 unsigned RevVTSize = ResVT.getSizeInBits();
1945 if (ValVT.getSizeInBits() <= 128 &&
1946 ((LT.second == MVT::v16i8 && RevVTSize <= 32) ||
1947 (LT.second == MVT::v8i16 && RevVTSize <= 64) ||
1948 (LT.second == MVT::v4i32 && RevVTSize <= 64)))
1949 return ST->getMVEVectorCostFactor(CostKind) * LT.first;
1950 }
1951
1952 return BaseT::getMulAccReductionCost(IsUnsigned, RedOpcode, ResTy, ValTy,
1953 CostKind);
1954}
1955
1958 FastMathFlags FMF,
1959 TTI::TargetCostKind CostKind) const {
1960 EVT ValVT = TLI->getValueType(DL, Ty);
1961
1962 // In general floating point reductions are a series of elementwise
1963 // operations, with free extracts on each step. These are either in-order or
1964 // treewise depending on whether that is allowed by the fast math flags.
1965 if ((IID == Intrinsic::minnum || IID == Intrinsic::maxnum) &&
1966 ((ValVT.getVectorElementType() == MVT::f32 && ST->hasVFP2Base()) ||
1967 (ValVT.getVectorElementType() == MVT::f64 && ST->hasFP64()) ||
1968 (ValVT.getVectorElementType() == MVT::f16 && ST->hasFullFP16()))) {
1969 unsigned NumElts = cast<FixedVectorType>(Ty)->getNumElements();
1970 unsigned EltSize = ValVT.getScalarSizeInBits();
1971 unsigned VecLimit = ST->hasMVEFloatOps() ? 128 : (ST->hasNEON() ? 64 : -1);
1972 InstructionCost VecCost;
1973 while (isPowerOf2_32(NumElts) && NumElts * EltSize > VecLimit) {
1974 Type *VecTy = FixedVectorType::get(Ty->getElementType(), NumElts/2);
1975 IntrinsicCostAttributes ICA(IID, VecTy, {VecTy, VecTy}, FMF);
1976 VecCost += getIntrinsicInstrCost(ICA, CostKind);
1977 NumElts /= 2;
1978 }
1979
1980 // For fp16 we need to extract the upper lane elements. MVE can add a
1981 // VREV+FMIN/MAX to perform another vector step instead.
1982 InstructionCost ExtractCost = 0;
1983 if (ST->hasMVEFloatOps() && ValVT.getVectorElementType() == MVT::f16 &&
1984 NumElts == 8) {
1985 VecCost += ST->getMVEVectorCostFactor(CostKind) * 2;
1986 NumElts /= 2;
1987 } else if (ValVT.getVectorElementType() == MVT::f16)
1988 ExtractCost = cast<FixedVectorType>(Ty)->getNumElements() / 2;
1989
1990 IntrinsicCostAttributes ICA(IID, Ty->getElementType(),
1991 {Ty->getElementType(), Ty->getElementType()},
1992 FMF);
1993 return VecCost + ExtractCost +
1994 (NumElts - 1) * getIntrinsicInstrCost(ICA, CostKind);
1995 }
1996
1997 if (IID == Intrinsic::smin || IID == Intrinsic::smax ||
1998 IID == Intrinsic::umin || IID == Intrinsic::umax) {
1999 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(Ty);
2000
2001 // All costs are the same for u/s min/max. These lower to vminv, which are
2002 // given a slightly higher cost as they tend to take multiple cycles for
2003 // smaller type sizes.
2004 static const CostTblEntry CostTblAdd[]{
2005 {ISD::SMIN, MVT::v16i8, 4},
2006 {ISD::SMIN, MVT::v8i16, 3},
2007 {ISD::SMIN, MVT::v4i32, 2},
2008 };
2009 if (const auto *Entry = CostTableLookup(CostTblAdd, ISD::SMIN, LT.second))
2010 return Entry->Cost * ST->getMVEVectorCostFactor(CostKind) * LT.first;
2011 }
2012
2013 return BaseT::getMinMaxReductionCost(IID, Ty, FMF, CostKind);
2014}
2015
2018 TTI::TargetCostKind CostKind) const {
2019 unsigned Opc = ICA.getID();
2020 switch (Opc) {
2021 case Intrinsic::get_active_lane_mask:
2022 // Currently we make a somewhat optimistic assumption that
2023 // active_lane_mask's are always free. In reality it may be freely folded
2024 // into a tail predicated loop, expanded into a VCPT or expanded into a lot
2025 // of add/icmp code. We may need to improve this in the future, but being
2026 // able to detect if it is free or not involves looking at a lot of other
2027 // code. We currently assume that the vectorizer inserted these, and knew
2028 // what it was doing in adding one.
2029 if (ST->hasMVEIntegerOps())
2030 return 0;
2031 break;
2032 case Intrinsic::sadd_sat:
2033 case Intrinsic::ssub_sat:
2034 case Intrinsic::uadd_sat:
2035 case Intrinsic::usub_sat: {
2036 bool IsAdd = (Opc == Intrinsic::sadd_sat || Opc == Intrinsic::ssub_sat);
2037 bool IsSigned = (Opc == Intrinsic::sadd_sat || Opc == Intrinsic::ssub_sat);
2038 Type *RetTy = ICA.getReturnType();
2039
2040 if (auto *ITy = dyn_cast<IntegerType>(RetTy)) {
2041 if (IsSigned && ST->hasDSP() && ITy->getBitWidth() == 32)
2042 return 1; // qadd / qsub
2043 if (ST->hasDSP() && (ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16))
2044 return 2; // uqadd16 / qadd16 / uqsub16 / qsub16 + possible extend.
2045 // Otherwise return the cost of expanding the node. Generally an add +
2046 // icmp + sel.
2048 Type *CondTy = RetTy->getWithNewBitWidth(1);
2049 return getArithmeticInstrCost(IsAdd ? Instruction::Add : Instruction::Sub,
2050 RetTy, CostKind) +
2051 2 * getCmpSelInstrCost(BinaryOperator::ICmp, RetTy, CondTy, Pred,
2052 CostKind) +
2053 2 * getCmpSelInstrCost(BinaryOperator::Select, RetTy, CondTy, Pred,
2054 CostKind);
2055 }
2056
2057 if (!ST->hasMVEIntegerOps())
2058 break;
2059
2060 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(RetTy);
2061 if (LT.second == MVT::v4i32 || LT.second == MVT::v8i16 ||
2062 LT.second == MVT::v16i8) {
2063 // This is a base cost of 1 for the vqadd, plus 3 extract shifts if we
2064 // need to extend the type, as it uses shr(qadd(shl, shl)).
2065 unsigned Instrs =
2066 LT.second.getScalarSizeInBits() == RetTy->getScalarSizeInBits() ? 1
2067 : 4;
2068 return LT.first * ST->getMVEVectorCostFactor(CostKind) * Instrs;
2069 }
2070 break;
2071 }
2072 case Intrinsic::abs:
2073 case Intrinsic::smin:
2074 case Intrinsic::smax:
2075 case Intrinsic::umin:
2076 case Intrinsic::umax: {
2077 if (!ST->hasMVEIntegerOps())
2078 break;
2079 Type *VT = ICA.getReturnType();
2080
2081 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(VT);
2082 if (LT.second == MVT::v4i32 || LT.second == MVT::v8i16 ||
2083 LT.second == MVT::v16i8)
2084 return LT.first * ST->getMVEVectorCostFactor(CostKind);
2085 break;
2086 }
2087 case Intrinsic::minnum:
2088 case Intrinsic::maxnum: {
2089 if (!ST->hasMVEFloatOps())
2090 break;
2091 Type *VT = ICA.getReturnType();
2092 std::pair<InstructionCost, MVT> LT = getTypeLegalizationCost(VT);
2093 if (LT.second == MVT::v4f32 || LT.second == MVT::v8f16)
2094 return LT.first * ST->getMVEVectorCostFactor(CostKind);
2095 break;
2096 }
2097 case Intrinsic::fptosi_sat:
2098 case Intrinsic::fptoui_sat: {
2099 if (ICA.getArgTypes().empty())
2100 break;
2101 bool IsSigned = Opc == Intrinsic::fptosi_sat;
2102 auto LT = getTypeLegalizationCost(ICA.getArgTypes()[0]);
2103 EVT MTy = TLI->getValueType(DL, ICA.getReturnType());
2104 // Check for the legal types, with the correct subtarget features.
2105 if ((ST->hasVFP2Base() && LT.second == MVT::f32 && MTy == MVT::i32) ||
2106 (ST->hasFP64() && LT.second == MVT::f64 && MTy == MVT::i32) ||
2107 (ST->hasFullFP16() && LT.second == MVT::f16 && MTy == MVT::i32))
2108 return LT.first;
2109
2110 // Equally for MVE vector types
2111 if (ST->hasMVEFloatOps() &&
2112 (LT.second == MVT::v4f32 || LT.second == MVT::v8f16) &&
2113 LT.second.getScalarSizeInBits() == MTy.getScalarSizeInBits())
2114 return LT.first * ST->getMVEVectorCostFactor(CostKind);
2115
2116 // If we can we use a legal convert followed by a min+max
2117 if (((ST->hasVFP2Base() && LT.second == MVT::f32) ||
2118 (ST->hasFP64() && LT.second == MVT::f64) ||
2119 (ST->hasFullFP16() && LT.second == MVT::f16) ||
2120 (ST->hasMVEFloatOps() &&
2121 (LT.second == MVT::v4f32 || LT.second == MVT::v8f16))) &&
2122 LT.second.getScalarSizeInBits() >= MTy.getScalarSizeInBits()) {
2123 Type *LegalTy = Type::getIntNTy(ICA.getReturnType()->getContext(),
2124 LT.second.getScalarSizeInBits());
2126 LT.second.isVector() ? ST->getMVEVectorCostFactor(CostKind) : 1;
2127 IntrinsicCostAttributes Attrs1(IsSigned ? Intrinsic::smin
2128 : Intrinsic::umin,
2129 LegalTy, {LegalTy, LegalTy});
2130 Cost += getIntrinsicInstrCost(Attrs1, CostKind);
2131 IntrinsicCostAttributes Attrs2(IsSigned ? Intrinsic::smax
2132 : Intrinsic::umax,
2133 LegalTy, {LegalTy, LegalTy});
2134 Cost += getIntrinsicInstrCost(Attrs2, CostKind);
2135 return LT.first * Cost;
2136 }
2137 // Otherwise we need to follow the default expansion that clamps the value
2138 // using a float min/max with a fcmp+sel for nan handling when signed.
2139 Type *FPTy = ICA.getArgTypes()[0];
2140 Type *RetTy = ICA.getReturnType();
2141 IntrinsicCostAttributes Attrs1(Intrinsic::minnum, FPTy, {FPTy, FPTy});
2142 InstructionCost Cost = getIntrinsicInstrCost(Attrs1, CostKind);
2143 IntrinsicCostAttributes Attrs2(Intrinsic::maxnum, FPTy, {FPTy, FPTy});
2144 Cost += getIntrinsicInstrCost(Attrs2, CostKind);
2145 Cost +=
2146 getCastInstrCost(IsSigned ? Instruction::FPToSI : Instruction::FPToUI,
2147 RetTy, FPTy, TTI::CastContextHint::None, CostKind);
2148 if (IsSigned) {
2149 Type *CondTy = RetTy->getWithNewBitWidth(1);
2150 Cost += getCmpSelInstrCost(BinaryOperator::FCmp, FPTy, CondTy,
2151 CmpInst::FCMP_UNO, CostKind);
2152 Cost += getCmpSelInstrCost(BinaryOperator::Select, RetTy, CondTy,
2153 CmpInst::FCMP_UNO, CostKind);
2154 }
2155 return Cost;
2156 }
2157 }
2158
2159 return BaseT::getIntrinsicInstrCost(ICA, CostKind);
2160}
2161
2163 if (!F->isIntrinsic())
2164 return BaseT::isLoweredToCall(F);
2165
2166 // Assume all Arm-specific intrinsics map to an instruction.
2167 if (F->getName().starts_with("llvm.arm"))
2168 return false;
2169
2170 switch (F->getIntrinsicID()) {
2171 default: break;
2172 case Intrinsic::powi:
2173 case Intrinsic::sin:
2174 case Intrinsic::cos:
2175 case Intrinsic::sincos:
2176 case Intrinsic::pow:
2177 case Intrinsic::log:
2178 case Intrinsic::log10:
2179 case Intrinsic::log2:
2180 case Intrinsic::exp:
2181 case Intrinsic::exp2:
2182 return true;
2183 case Intrinsic::sqrt:
2184 case Intrinsic::fabs:
2185 case Intrinsic::copysign:
2186 case Intrinsic::floor:
2187 case Intrinsic::ceil:
2188 case Intrinsic::trunc:
2189 case Intrinsic::rint:
2190 case Intrinsic::nearbyint:
2191 case Intrinsic::round:
2192 case Intrinsic::canonicalize:
2193 case Intrinsic::lround:
2194 case Intrinsic::llround:
2195 case Intrinsic::lrint:
2196 case Intrinsic::llrint:
2197 if (F->getReturnType()->isDoubleTy() && !ST->hasFP64())
2198 return true;
2199 if (F->getReturnType()->isHalfTy() && !ST->hasFullFP16())
2200 return true;
2201 // Some operations can be handled by vector instructions and assume
2202 // unsupported vectors will be expanded into supported scalar ones.
2203 // TODO Handle scalar operations properly.
2204 return !ST->hasFPARMv8Base() && !ST->hasVFP2Base();
2205 case Intrinsic::masked_store:
2206 case Intrinsic::masked_load:
2207 case Intrinsic::masked_gather:
2208 case Intrinsic::masked_scatter:
2209 return !ST->hasMVEIntegerOps();
2210 case Intrinsic::sadd_with_overflow:
2211 case Intrinsic::uadd_with_overflow:
2212 case Intrinsic::ssub_with_overflow:
2213 case Intrinsic::usub_with_overflow:
2214 case Intrinsic::sadd_sat:
2215 case Intrinsic::uadd_sat:
2216 case Intrinsic::ssub_sat:
2217 case Intrinsic::usub_sat:
2218 return false;
2219 }
2220
2221 return BaseT::isLoweredToCall(F);
2222}
2223
2225 unsigned ISD = TLI->InstructionOpcodeToISD(I.getOpcode());
2226 EVT VT = TLI->getValueType(DL, I.getType(), true);
2227 if (TLI->getOperationAction(ISD, VT) == TargetLowering::LibCall)
2228 return true;
2229
2230 // Check if an intrinsic will be lowered to a call and assume that any
2231 // other CallInst will generate a bl.
2232 if (auto *Call = dyn_cast<CallInst>(&I)) {
2233 if (auto *II = dyn_cast<IntrinsicInst>(Call)) {
2234 switch(II->getIntrinsicID()) {
2235 case Intrinsic::memcpy:
2236 case Intrinsic::memset:
2237 case Intrinsic::memmove:
2238 return getNumMemOps(II) == -1;
2239 default:
2240 if (const Function *F = Call->getCalledFunction())
2241 return isLoweredToCall(F);
2242 }
2243 }
2244 return true;
2245 }
2246
2247 // FPv5 provides conversions between integer, double-precision,
2248 // single-precision, and half-precision formats.
2249 switch (I.getOpcode()) {
2250 default:
2251 break;
2252 case Instruction::FPToSI:
2253 case Instruction::FPToUI:
2254 case Instruction::SIToFP:
2255 case Instruction::UIToFP:
2256 case Instruction::FPTrunc:
2257 case Instruction::FPExt:
2258 return !ST->hasFPARMv8Base();
2259 }
2260
2261 // FIXME: Unfortunately the approach of checking the Operation Action does
2262 // not catch all cases of Legalization that use library calls. Our
2263 // Legalization step categorizes some transformations into library calls as
2264 // Custom, Expand or even Legal when doing type legalization. So for now
2265 // we have to special case for instance the SDIV of 64bit integers and the
2266 // use of floating point emulation.
2267 if (VT.isInteger() && VT.getSizeInBits() >= 64) {
2268 switch (ISD) {
2269 default:
2270 break;
2271 case ISD::SDIV:
2272 case ISD::UDIV:
2273 case ISD::SREM:
2274 case ISD::UREM:
2275 case ISD::SDIVREM:
2276 case ISD::UDIVREM:
2277 return true;
2278 }
2279 }
2280
2281 // Assume all other non-float operations are supported.
2282 if (!VT.isFloatingPoint())
2283 return false;
2284
2285 // We'll need a library call to handle most floats when using soft.
2286 if (TLI->useSoftFloat()) {
2287 switch (I.getOpcode()) {
2288 default:
2289 return true;
2290 case Instruction::Alloca:
2291 case Instruction::Load:
2292 case Instruction::Store:
2293 case Instruction::Select:
2294 case Instruction::PHI:
2295 return false;
2296 }
2297 }
2298
2299 // We'll need a libcall to perform double precision operations on a single
2300 // precision only FPU.
2301 if (I.getType()->isDoubleTy() && !ST->hasFP64())
2302 return true;
2303
2304 // Likewise for half precision arithmetic.
2305 if (I.getType()->isHalfTy() && !ST->hasFullFP16())
2306 return true;
2307
2308 return false;
2309}
2310
2312 AssumptionCache &AC,
2313 TargetLibraryInfo *LibInfo,
2314 HardwareLoopInfo &HWLoopInfo) const {
2315 // Low-overhead branches are only supported in the 'low-overhead branch'
2316 // extension of v8.1-m.
2317 if (!ST->hasV8_1MMainlineOps() || !ST->hasLOB() || !ST->getCLOpts().loloops) {
2318 LLVM_DEBUG(dbgs() << "ARMHWLoops: Disabled\n");
2319 return false;
2320 }
2321
2323 LLVM_DEBUG(dbgs() << "ARMHWLoops: No BETC\n");
2324 return false;
2325 }
2326
2327 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
2328 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
2329 LLVM_DEBUG(dbgs() << "ARMHWLoops: Uncomputable BETC\n");
2330 return false;
2331 }
2332
2333 const SCEV *TripCountSCEV =
2334 SE.getAddExpr(BackedgeTakenCount,
2335 SE.getOne(BackedgeTakenCount->getType()));
2336
2337 // We need to store the trip count in LR, a 32-bit register.
2338 if (SE.getUnsignedRangeMax(TripCountSCEV).getBitWidth() > 32) {
2339 LLVM_DEBUG(dbgs() << "ARMHWLoops: Trip count does not fit into 32bits\n");
2340 return false;
2341 }
2342
2343 // Making a call will trash LR and clear LO_BRANCH_INFO, so there's little
2344 // point in generating a hardware loop if that's going to happen.
2345
2346 auto IsHardwareLoopIntrinsic = [](Instruction &I) {
2347 if (auto *Call = dyn_cast<IntrinsicInst>(&I)) {
2348 switch (Call->getIntrinsicID()) {
2349 default:
2350 break;
2351 case Intrinsic::start_loop_iterations:
2352 case Intrinsic::test_start_loop_iterations:
2353 case Intrinsic::loop_decrement:
2354 case Intrinsic::loop_decrement_reg:
2355 return true;
2356 }
2357 }
2358 return false;
2359 };
2360
2361 // Scan the instructions to see if there's any that we know will turn into a
2362 // call or if this loop is already a low-overhead loop or will become a tail
2363 // predicated loop.
2364 bool IsTailPredLoop = false;
2365 auto ScanLoop = [&](Loop *L) {
2366 for (auto *BB : L->getBlocks()) {
2367 for (auto &I : *BB) {
2368 if (maybeLoweredToCall(I) || IsHardwareLoopIntrinsic(I) ||
2369 isa<InlineAsm>(I)) {
2370 LLVM_DEBUG(dbgs() << "ARMHWLoops: Bad instruction: " << I << "\n");
2371 return false;
2372 }
2373 if (auto *II = dyn_cast<IntrinsicInst>(&I))
2374 IsTailPredLoop |=
2375 II->getIntrinsicID() == Intrinsic::get_active_lane_mask ||
2376 II->getIntrinsicID() == Intrinsic::arm_mve_vctp8 ||
2377 II->getIntrinsicID() == Intrinsic::arm_mve_vctp16 ||
2378 II->getIntrinsicID() == Intrinsic::arm_mve_vctp32 ||
2379 II->getIntrinsicID() == Intrinsic::arm_mve_vctp64;
2380 }
2381 }
2382 return true;
2383 };
2384
2385 // Visit inner loops.
2386 for (auto *Inner : *L)
2387 if (!ScanLoop(Inner))
2388 return false;
2389
2390 if (!ScanLoop(L))
2391 return false;
2392
2393 // TODO: Check whether the trip count calculation is expensive. If L is the
2394 // inner loop but we know it has a low trip count, calculating that trip
2395 // count (in the parent loop) may be detrimental.
2396
2397 LLVMContext &C = L->getHeader()->getContext();
2398 HWLoopInfo.CounterInReg = true;
2399 HWLoopInfo.IsNestingLegal = false;
2400 HWLoopInfo.PerformEntryTest =
2401 ST->getCLOpts().allow_wlsloops && !IsTailPredLoop;
2402 HWLoopInfo.CountType = Type::getInt32Ty(C);
2403 HWLoopInfo.LoopDecrement = ConstantInt::get(HWLoopInfo.CountType, 1);
2404 return true;
2405}
2406
2407static bool canTailPredicateInstruction(Instruction &I, int &ICmpCount) {
2408 // We don't allow icmp's, and because we only look at single block loops,
2409 // we simply count the icmps, i.e. there should only be 1 for the backedge.
2410 if (isa<ICmpInst>(&I) && ++ICmpCount > 1)
2411 return false;
2412 // FIXME: This is a workaround for poor cost modelling. Min/Max intrinsics are
2413 // not currently canonical, but soon will be. Code without them uses icmp, and
2414 // so is not tail predicated as per the condition above. In order to get the
2415 // same performance we treat min and max the same as an icmp for tailpred
2416 // purposes for the moment (we often rely on non-tailpred and higher VF's to
2417 // pick more optimal instructions like VQDMULH. They need to be recognized
2418 // directly by the vectorizer).
2419 if (auto *II = dyn_cast<IntrinsicInst>(&I))
2420 if ((II->getIntrinsicID() == Intrinsic::smin ||
2421 II->getIntrinsicID() == Intrinsic::smax ||
2422 II->getIntrinsicID() == Intrinsic::umin ||
2423 II->getIntrinsicID() == Intrinsic::umax) &&
2424 ++ICmpCount > 1)
2425 return false;
2426
2427 if (isa<FCmpInst>(&I))
2428 return false;
2429
2430 // We could allow extending/narrowing FP loads/stores, but codegen is
2431 // too inefficient so reject this for now.
2433 return false;
2434
2435 // Extends have to be extending-loads
2436 if (isa<SExtInst>(&I) || isa<ZExtInst>(&I) )
2437 if (!I.getOperand(0)->hasOneUse() || !isa<LoadInst>(I.getOperand(0)))
2438 return false;
2439
2440 // Truncs have to be narrowing-stores
2441 if (isa<TruncInst>(&I) )
2442 if (!I.hasOneUse() || !isa<StoreInst>(*I.user_begin()))
2443 return false;
2444
2445 return true;
2446}
2447
2448// To set up a tail-predicated loop, we need to know the total number of
2449// elements processed by that loop. Thus, we need to determine the element
2450// size and:
2451// 1) it should be uniform for all operations in the vector loop, so we
2452// e.g. don't want any widening/narrowing operations.
2453// 2) it should be smaller than i64s because we don't have vector operations
2454// that work on i64s.
2455// 3) we don't want elements to be reversed or shuffled, to make sure the
2456// tail-predication masks/predicates the right lanes.
2457//
2458static bool canTailPredicateLoop(const ARMOptions &CLOpts, Loop *L,
2459 LoopInfo *LI, ScalarEvolution &SE,
2460 const DataLayout &DL,
2461 const LoopAccessInfo *LAI,
2462 const DominatorTree &DT) {
2463 LLVM_DEBUG(dbgs() << "Tail-predication: checking allowed instructions\n");
2464
2465 // If there are live-out values, it is probably a reduction. We can predicate
2466 // most reduction operations freely under MVE using a combination of
2467 // prefer-predicated-reduction-select and inloop reductions. We limit this to
2468 // floating point and integer reductions, but don't check for operators
2469 // specifically here. If the value ends up not being a reduction (and so the
2470 // vectorizer cannot tailfold the loop), we should fall back to standard
2471 // vectorization automatically.
2473 LiveOuts = llvm::findDefsUsedOutsideOfLoop(L);
2474 bool ReductionsDisabled =
2475 CLOpts.tail_predication == TailPredication::EnabledNoReductions ||
2476 CLOpts.tail_predication == TailPredication::ForceEnabledNoReductions;
2477
2478 for (auto *I : LiveOuts) {
2479 if (!I->getType()->isIntegerTy() && !I->getType()->isFloatTy() &&
2480 !I->getType()->isHalfTy()) {
2481 LLVM_DEBUG(dbgs() << "Don't tail-predicate loop with non-integer/float "
2482 "live-out value\n");
2483 return false;
2484 }
2485 if (ReductionsDisabled) {
2486 LLVM_DEBUG(dbgs() << "Reductions not enabled\n");
2487 return false;
2488 }
2489 }
2490
2491 // Next, check that all instructions can be tail-predicated.
2492 PredicatedScalarEvolution PSE = LAI->getPSE();
2493 int ICmpCount = 0;
2494
2495 for (BasicBlock *BB : L->blocks()) {
2496 for (Instruction &I : *BB) {
2498 continue;
2499 if (!canTailPredicateInstruction(I, ICmpCount)) {
2500 LLVM_DEBUG(dbgs() << "Instruction not allowed: "; I.dump());
2501 return false;
2502 }
2503
2504 Type *T = I.getType();
2505 if (T->getScalarSizeInBits() > 32) {
2506 LLVM_DEBUG(dbgs() << "Unsupported Type: "; T->dump());
2507 return false;
2508 }
2509 if (isa<StoreInst>(I) || isa<LoadInst>(I)) {
2511 Type *AccessTy = getLoadStoreType(&I);
2512 int64_t NextStride =
2513 getPtrStride(PSE, AccessTy, Ptr, L, DT).value_or(0);
2514 if (NextStride == 1) {
2515 // TODO: for now only allow consecutive strides of 1. We could support
2516 // other strides as long as it is uniform, but let's keep it simple
2517 // for now.
2518 continue;
2519 } else if (NextStride == -1 ||
2520 (NextStride == 2 && CLOpts.mve_max_interleave_factor >= 2) ||
2521 (NextStride == 4 && CLOpts.mve_max_interleave_factor >= 4)) {
2523 << "Consecutive strides of 2 found, vld2/vstr2 can't "
2524 "be tail-predicated\n.");
2525 return false;
2526 // TODO: don't tail predicate if there is a reversed load?
2527 } else if (CLOpts.maskedgatscat) {
2528 // Gather/scatters do allow loading from arbitrary strides, at
2529 // least if they are loop invariant.
2530 // TODO: Loop variant strides should in theory work, too, but
2531 // this requires further testing.
2532 const SCEV *PtrScev = PSE.getSE()->getSCEV(Ptr);
2533 if (auto AR = dyn_cast<SCEVAddRecExpr>(PtrScev)) {
2534 const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
2535 if (PSE.getSE()->isLoopInvariant(Step, L))
2536 continue;
2537 }
2538 }
2539 LLVM_DEBUG(dbgs() << "Bad stride found, can't "
2540 "tail-predicate\n.");
2541 return false;
2542 }
2543 }
2544 }
2545
2546 LLVM_DEBUG(dbgs() << "tail-predication: all instructions allowed!\n");
2547 return true;
2548}
2549
2551 if (ST->getCLOpts().tail_predication == TailPredication::Disabled) {
2552 LLVM_DEBUG(dbgs() << "Tail-folding not enabled.\n");
2553 return false;
2554 }
2555
2556 // Creating a tail-folded vector loop is the first step for generating a
2557 // tail-folded hardware loop, for which we need the MVE masked
2558 // load/stores instructions:
2559 if (!ST->hasMVEIntegerOps())
2560 return false;
2561
2562 LoopVectorizationLegality *LVL = TFI->LVL;
2563 Loop *L = LVL->getLoop();
2564
2565 // For now, restrict this to single block loops.
2566 if (L->getNumBlocks() > 1) {
2567 LLVM_DEBUG(dbgs() << "preferTailFoldingOverEpilogue: not a single block "
2568 "loop.\n");
2569 return false;
2570 }
2571
2572 assert(L->isInnermost() &&
2573 "preferTailFoldingOverEpilogue: inner-loop expected");
2574
2575 LoopInfo *LI = LVL->getLoopInfo();
2576 HardwareLoopInfo HWLoopInfo(L);
2577 if (!HWLoopInfo.canAnalyze(*LI)) {
2578 LLVM_DEBUG(dbgs() << "preferTailFoldingOverEpilogue: hardware-loop is not "
2579 "analyzable.\n");
2580 return false;
2581 }
2582
2585
2586 // This checks if we have the low-overhead branch architecture
2587 // extension, and if we will create a hardware-loop:
2588 if (!isHardwareLoopProfitable(L, *SE, *AC, TFI->TLI, HWLoopInfo)) {
2589 LLVM_DEBUG(dbgs() << "preferTailFoldingOverEpilogue: hardware-loop is not "
2590 "profitable.\n");
2591 return false;
2592 }
2593
2594 DominatorTree *DT = LVL->getDominatorTree();
2595 if (!HWLoopInfo.isHardwareLoopCandidate(*SE, *LI, *DT)) {
2596 LLVM_DEBUG(dbgs() << "preferTailFoldingOverEpilogue: hardware-loop is not "
2597 "a candidate.\n");
2598 return false;
2599 }
2600
2601 return canTailPredicateLoop(ST->getCLOpts(), L, LI, *SE, DL, LVL->getLAI(),
2602 *LVL->getDominatorTree());
2603}
2604
2606 if (!ST->hasMVEIntegerOps() ||
2607 ST->getCLOpts().tail_predication == TailPredication::Disabled)
2609
2610 // Intrinsic @llvm.get.active.lane.mask is supported.
2611 // It is used in the MVETailPredication pass, which requires the number of
2612 // elements processed by this vector loop to setup the tail-predicated
2613 // loop.
2615}
2618 OptimizationRemarkEmitter *ORE) const {
2619 // Enable Upper bound unrolling universally, providing that we do not see an
2620 // active lane mask, which will be better kept as a loop to become tail
2621 // predicated than to be conditionally unrolled.
2622 UP.UpperBound =
2623 !ST->hasMVEIntegerOps() || !any_of(*L->getHeader(), [](Instruction &I) {
2624 return isa<IntrinsicInst>(I) &&
2625 cast<IntrinsicInst>(I).getIntrinsicID() ==
2626 Intrinsic::get_active_lane_mask;
2627 });
2628
2629 // Only currently enable these preferences for M-Class cores.
2630 if (!ST->isMClass())
2631 return BasicTTIImplBase::getUnrollingPreferences(L, SE, UP, ORE);
2632
2633 // Disable loop unrolling for Oz and Os.
2634 UP.OptSizeThreshold = 0;
2636 if (L->getHeader()->getParent()->hasOptSize())
2637 return;
2638
2639 SmallVector<BasicBlock*, 4> ExitingBlocks;
2640 L->getExitingBlocks(ExitingBlocks);
2641 LLVM_DEBUG(dbgs() << "Loop has:\n"
2642 << "Blocks: " << L->getNumBlocks() << "\n"
2643 << "Exit blocks: " << ExitingBlocks.size() << "\n");
2644
2645 // Only allow another exit other than the latch. This acts as an early exit
2646 // as it mirrors the profitability calculation of the runtime unroller.
2647 if (ExitingBlocks.size() > 2)
2648 return;
2649
2650 // Limit the CFG of the loop body for targets with a branch predictor.
2651 // Allowing 4 blocks permits if-then-else diamonds in the body.
2652 if (ST->hasBranchPredictor() && L->getNumBlocks() > 4)
2653 return;
2654
2655 // Don't unroll vectorized loops, including the remainder loop
2656 if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
2657 return;
2658
2659 // Scan the loop: don't unroll loops with calls as this could prevent
2660 // inlining.
2662 for (auto *BB : L->getBlocks()) {
2663 for (auto &I : *BB) {
2664 // Don't unroll vectorised loop. MVE does not benefit from it as much as
2665 // scalar code.
2666 if (I.getType()->isVectorTy())
2667 return;
2668
2669 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
2670 if (const Function *F = cast<CallBase>(I).getCalledFunction()) {
2671 if (!isLoweredToCall(F))
2672 continue;
2673 }
2674 return;
2675 }
2676
2677 SmallVector<const Value*, 4> Operands(I.operand_values());
2680 }
2681 }
2682
2683 // On v6m cores, there are very few registers available. We can easily end up
2684 // spilling and reloading more registers in an unrolled loop. Look at the
2685 // number of LCSSA phis as a rough measure of how many registers will need to
2686 // be live out of the loop, reducing the default unroll count if more than 1
2687 // value is needed. In the long run, all of this should be being learnt by a
2688 // machine.
2689 unsigned UnrollCount = 4;
2690 if (ST->isThumb1Only()) {
2691 unsigned ExitingValues = 0;
2693 L->getExitBlocks(ExitBlocks);
2694 for (auto *Exit : ExitBlocks) {
2695 // Count the number of LCSSA phis. Exclude values coming from GEP's as
2696 // only the last is expected to be needed for address operands.
2697 unsigned LiveOuts = count_if(Exit->phis(), [](auto &PH) {
2698 return PH.getNumOperands() != 1 ||
2699 !isa<GetElementPtrInst>(PH.getOperand(0));
2700 });
2701 ExitingValues = ExitingValues < LiveOuts ? LiveOuts : ExitingValues;
2702 }
2703 if (ExitingValues)
2704 UnrollCount /= ExitingValues;
2705 if (UnrollCount <= 1)
2706 return;
2707 }
2708
2709 // For processors with low overhead branching (LOB), runtime unrolling the
2710 // innermost loop is often detrimental to performance. In these cases the loop
2711 // remainder gets unrolled into a series of compare-and-jump blocks, which in
2712 // deeply nested loops get executed multiple times, negating the benefits of
2713 // LOB. This is particularly noticeable when the loop trip count of the
2714 // innermost loop varies within the outer loop, such as in the case of
2715 // triangular matrix decompositions. In these cases we will prefer to not
2716 // unroll the innermost loop, with the intention for it to be executed as a
2717 // low overhead loop.
2718 bool Runtime = true;
2719 if (ST->hasLOB()) {
2721 const SCEV *BETC = SE.getBackedgeTakenCount(L);
2722 auto *Outer = L->getOutermostLoop();
2723 if ((L != Outer && Outer != L->getParentLoop()) ||
2724 (L != Outer && BETC && !SE.isLoopInvariant(BETC, Outer))) {
2725 Runtime = false;
2726 }
2727 }
2728 }
2729
2730 LLVM_DEBUG(dbgs() << "Cost of loop: " << Cost << "\n");
2731 LLVM_DEBUG(dbgs() << "Default Runtime Unroll Count: " << UnrollCount << "\n");
2732
2733 UP.Partial = true;
2734 UP.Runtime = Runtime;
2735 UP.UnrollRemainder = true;
2736 UP.DefaultUnrollRuntimeCount = UnrollCount;
2737 UP.UnrollAndJam = true;
2739
2740 // Force unrolling small loops can be very useful because of the branch
2741 // taken cost of the backedge.
2742 if (Cost < ST->getCLOpts().force_unroll_threshold)
2743 UP.Force = true;
2744}
2745
2750
2752 if (!ST->hasMVEIntegerOps())
2753 return false;
2754
2755 unsigned ScalarBits = Ty->getScalarSizeInBits();
2756 switch (Kind) {
2757 case RecurKind::Add:
2758 return ScalarBits <= 64;
2759 default:
2760 return false;
2761 }
2762}
2763
2765 if (!ST->hasMVEIntegerOps())
2766 return false;
2767 return true;
2768}
2769
2771 StackOffset BaseOffset,
2772 bool HasBaseReg, int64_t Scale,
2773 unsigned AddrSpace) const {
2775 AM.BaseGV = BaseGV;
2776 AM.BaseOffs = BaseOffset.getFixed();
2777 AM.HasBaseReg = HasBaseReg;
2778 AM.Scale = Scale;
2779 AM.ScalableOffset = BaseOffset.getScalable();
2780 if (getTLI()->isLegalAddressingMode(DL, AM, Ty, AddrSpace)) {
2781 if (ST->hasFPAO())
2782 return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
2783 return 0;
2784 }
2786}
2787
2789 // MVE only has 8 vector registers, so we should consider register pressure to
2790 // avoid vectorizing when the cost of spills exceeds the gains from
2791 // vectorization.
2792 return ST->hasMVEIntegerOps();
2793}
2794
2795bool ARMTTIImpl::hasArmWideBranch(bool Thumb) const {
2796 if (Thumb) {
2797 // B.W is available in any Thumb2-supporting target, and also in every
2798 // version of Armv8-M, even Baseline which does not include the rest of
2799 // Thumb2.
2800 return ST->isThumb2() || ST->hasV8MBaselineOps();
2801 } else {
2802 // B is available in all versions of the Arm ISA, so the only question is
2803 // whether that ISA is available at all.
2804 return ST->hasARMOps();
2805 }
2806}
2807
2808/// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
2809/// of the vector elements.
2810static bool areExtractExts(Value *Ext1, Value *Ext2) {
2811 using namespace PatternMatch;
2812
2813 auto areExtDoubled = [](Instruction *Ext) {
2814 return Ext->getType()->getScalarSizeInBits() ==
2815 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
2816 };
2817
2818 if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
2819 !match(Ext2, m_ZExtOrSExt(m_Value())) ||
2820 !areExtDoubled(cast<Instruction>(Ext1)) ||
2821 !areExtDoubled(cast<Instruction>(Ext2)))
2822 return false;
2823
2824 return true;
2825}
2826
2827/// Check if sinking \p I's operands to I's basic block is profitable, because
2828/// the operands can be folded into a target instruction, e.g.
2829/// sext/zext can be folded into vsubl.
2831 SmallVectorImpl<Use *> &Ops) const {
2832 using namespace PatternMatch;
2833
2834 if (!I->getType()->isVectorTy())
2835 return false;
2836
2837 if (ST->hasNEON()) {
2838 switch (I->getOpcode()) {
2839 case Instruction::Sub:
2840 case Instruction::Add: {
2841 if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
2842 return false;
2843 Ops.push_back(&I->getOperandUse(0));
2844 Ops.push_back(&I->getOperandUse(1));
2845 return true;
2846 }
2847 default:
2848 return false;
2849 }
2850 }
2851
2852 if (!ST->hasMVEIntegerOps())
2853 return false;
2854
2855 auto IsFMSMul = [&](Instruction *I) {
2856 if (!I->hasOneUse())
2857 return false;
2858 auto *Sub = *I->users().begin();
2859 return Sub->getOpcode() == Instruction::FSub && Sub->getOperand(1) == I;
2860 };
2861 auto IsFMS = [&](Instruction *I) {
2862 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
2863 if (match(I->getOperand(0), m_FNegOrFSubNegZero(m_Value())) ||
2864 match(I->getOperand(1), m_FNegOrFSubNegZero(m_Value())))
2865 return true;
2866 return false;
2867 };
2868
2869 auto IsSinker = [&](Instruction *I, int Operand) {
2870 switch (I->getOpcode()) {
2871 case Instruction::Add:
2872 case Instruction::Mul:
2873 case Instruction::FAdd:
2874 case Instruction::ICmp:
2875 case Instruction::FCmp:
2876 return true;
2877 case Instruction::FMul:
2878 return !IsFMSMul(I);
2879 case Instruction::Sub:
2880 case Instruction::FSub:
2881 case Instruction::Shl:
2882 case Instruction::LShr:
2883 case Instruction::AShr:
2884 return Operand == 1;
2885 case Instruction::Call:
2886 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2887 switch (II->getIntrinsicID()) {
2888 case Intrinsic::fma:
2889 return !IsFMS(I);
2890 case Intrinsic::sadd_sat:
2891 case Intrinsic::uadd_sat:
2892 case Intrinsic::arm_mve_add_predicated:
2893 case Intrinsic::arm_mve_mul_predicated:
2894 case Intrinsic::arm_mve_qadd_predicated:
2895 case Intrinsic::arm_mve_vhadd:
2896 case Intrinsic::arm_mve_hadd_predicated:
2897 case Intrinsic::arm_mve_vqdmull:
2898 case Intrinsic::arm_mve_vqdmull_predicated:
2899 case Intrinsic::arm_mve_vqdmulh:
2900 case Intrinsic::arm_mve_qdmulh_predicated:
2901 case Intrinsic::arm_mve_vqrdmulh:
2902 case Intrinsic::arm_mve_qrdmulh_predicated:
2903 case Intrinsic::arm_mve_fma_predicated:
2904 return true;
2905 case Intrinsic::ssub_sat:
2906 case Intrinsic::usub_sat:
2907 case Intrinsic::arm_mve_sub_predicated:
2908 case Intrinsic::arm_mve_qsub_predicated:
2909 case Intrinsic::arm_mve_hsub_predicated:
2910 case Intrinsic::arm_mve_vhsub:
2911 return Operand == 1;
2912 default:
2913 return false;
2914 }
2915 }
2916 return false;
2917 default:
2918 return false;
2919 }
2920 };
2921
2922 for (auto OpIdx : enumerate(I->operands())) {
2923 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
2924 // Make sure we are not already sinking this operand
2925 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
2926 continue;
2927
2928 Instruction *Shuffle = Op;
2929 if (Shuffle->getOpcode() == Instruction::BitCast)
2930 Shuffle = dyn_cast<Instruction>(Shuffle->getOperand(0));
2931 // We are looking for a splat that can be sunk.
2932 if (!Shuffle || !match(Shuffle, m_Shuffle(m_InsertElt(m_Undef(), m_Value(),
2933 m_ZeroInt()),
2934 m_Undef(), m_ZeroMask())))
2935 continue;
2936 if (!IsSinker(I, OpIdx.index()))
2937 continue;
2938
2939 // All uses of the shuffle should be sunk to avoid duplicating it across gpr
2940 // and vector registers
2941 for (Use &U : Op->uses()) {
2942 Instruction *Insn = cast<Instruction>(U.getUser());
2943 if (!IsSinker(Insn, U.getOperandNo()))
2944 return false;
2945 }
2946
2947 Ops.push_back(&Shuffle->getOperandUse(0));
2948 if (Shuffle != Op)
2949 Ops.push_back(&Op->getOperandUse(0));
2950 Ops.push_back(&OpIdx.value());
2951 }
2952 return true;
2953}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool areExtractExts(Value *Ext1, Value *Ext2)
Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth of the vector elements.
uint64_t Imm
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static bool canTailPredicateLoop(const ARMOptions &CLOpts, Loop *L, LoopInfo *LI, ScalarEvolution &SE, const DataLayout &DL, const LoopAccessInfo *LAI, const DominatorTree &DT)
static Value * isSSATMinMaxPattern(Instruction *Inst, const APInt &Imm)
static Value * simplifyNeonVld1(const IntrinsicInst &II, unsigned MemAlign, InstCombiner::BuilderTy &Builder)
Convert a vector load intrinsic into a simple llvm load instruction.
static bool isFPSatMinMaxPattern(Instruction *Inst, const APInt &Imm)
static bool canTailPredicateInstruction(Instruction &I, int &ICmpCount)
This file a TargetTransformInfoImplBase conforming object specific to the ARM target machine.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
Cost tables and simple lookup functions.
Hexagon Common GEP
This file provides the interface for the instcombine pass implementation.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
unsigned Opc
This file defines the LoopVectorizationLegality class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
static const Function * getCalledFunction(const MachineInstr &MI)
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
SI Fold Operands
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
static LLVM_ABI APInt getSplat(unsigned NewLen, const APInt &V)
Return a value containing V broadcasted over NewLen bits.
Definition APInt.cpp:648
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
InstructionCost getGatherScatterOpCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind) const
InstructionCost getVectorInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, unsigned Index, const Value *Op0, const Value *Op1, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
InstructionCost getMaskedMemoryOpCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind) const
InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, TTI::OperandValueInfo OpInfo={TTI::OK_AnyValue, TTI::OP_None}, const Instruction *I=nullptr) const override
InstructionCost getMemcpyCost(const Instruction *I) const override
bool maybeLoweredToCall(Instruction &I) const
bool preferInLoopReduction(RecurKind Kind, Type *Ty) const override
InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Op1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Op2Info={TTI::OK_AnyValue, TTI::OP_None}, const Instruction *I=nullptr) const override
InstructionCost getMulAccReductionCost(bool IsUnsigned, unsigned RedOpcode, Type *ResTy, VectorType *ValTy, TTI::TargetCostKind CostKind) const override
InstructionCost getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef< unsigned > Indices, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, bool UseMaskForCond=false, bool UseMaskForGaps=false) const override
InstructionCost getIntImmCost(const APInt &Imm, Type *Ty, TTI::TargetCostKind CostKind) const override
bool hasArmWideBranch(bool Thumb) const override
bool shouldConsiderVectorizationRegPressure() const override
bool preferTailFoldingOverEpilogue(TailFoldingInfo *TFI) const override
InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const override
int getNumMemOps(const IntrinsicInst *I) const
Given a memcpy/memset/memmove instruction, return the number of memory operations performed,...
InstructionCost getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const override
InstructionCost getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx, const APInt &Imm, Type *Ty) const override
InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Op1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Op2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr, ArrayRef< const Value * > Scalars={}) const override
bool isLoweredToCall(const Function *F) const override
InstructionCost getExtendedReductionCost(unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *ValTy, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind) const override
bool isProfitableToSinkOperands(Instruction *I, SmallVectorImpl< Use * > &Ops) const override
Check if sinking I's operands to I's basic block is profitable, because the operands can be folded in...
bool isLegalMaskedStore(Type *DataTy, Align Alignment, unsigned AddressSpace, TTI::MaskKind MaskKind=TTI::MaskKind::VariableOrConstantMask) const override
InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *ValTy, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind) const override
std::optional< Value * > simplifyDemandedVectorEltsIntrinsic(InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, APInt &UndefElts2, APInt &UndefElts3, std::function< void(Instruction *, unsigned, APInt, APInt &)> SimplifyAndSetOp) const override
bool isLegalMaskedLoad(Type *DataTy, Align Alignment, unsigned AddressSpace, TTI::MaskKind MaskKind=TTI::MaskKind::VariableOrConstantMask) const override
TailFoldingStyle getPreferredTailFoldingStyle() const override
InstructionCost getIntImmCostInst(unsigned Opcode, unsigned Idx, const APInt &Imm, Type *Ty, TTI::TargetCostKind CostKind, Instruction *Inst=nullptr) const override
InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const override
std::optional< Instruction * > instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const override
void getPeelingPreferences(Loop *L, ScalarEvolution &SE, TTI::PeelingPreferences &PP) const override
InstructionCost getMinMaxReductionCost(Intrinsic::ID IID, VectorType *Ty, FastMathFlags FMF, TTI::TargetCostKind CostKind) const override
TTI::AddressingModeKind getPreferredAddressingMode(const Loop *L, ScalarEvolution *SE) const override
InstructionCost getMemIntrinsicInstrCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind) const override
bool preferPredicatedReductionSelect() const override
bool isLegalMaskedGather(Type *Ty, Align Alignment) const override
InstructionCost getAddressComputationCost(Type *Ty, ScalarEvolution *SE, const SCEV *Ptr, TTI::TargetCostKind CostKind) const override
InstructionCost getShuffleCost(TTI::ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy, TTI::TargetCostKind CostKind, ArrayRef< int > Mask, int Index, VectorType *SubTp, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
bool isProfitableLSRChainElement(Instruction *I) const override
bool isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE, AssumptionCache &AC, TargetLibraryInfo *LibInfo, HardwareLoopInfo &HWLoopInfo) const override
void getUnrollingPreferences(Loop *L, ScalarEvolution &SE, TTI::UnrollingPreferences &UP, OptimizationRemarkEmitter *ORE) const override
InstructionCost getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, StackOffset BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace) const override
getScalingFactorCost - Return the cost of the scaling used in addressing mode represented by AM.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A cache of @llvm.assume calls within a function.
static LLVM_ABI Attribute getWithAlignment(LLVMContext &Context, Align Alignment)
Return a uniquified Attribute object that has the specific alignment set.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
InstructionCost getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef< unsigned > Indices, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, bool UseMaskForCond=false, bool UseMaskForGaps=false) const override
InstructionCost getMinMaxReductionCost(Intrinsic::ID IID, VectorType *Ty, FastMathFlags FMF, TTI::TargetCostKind CostKind) const override
InstructionCost getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const override
TTI::ShuffleKind improveShuffleKindFromMask(TTI::ShuffleKind Kind, ArrayRef< int > Mask, VectorType *SrcTy, int &Index, VectorType *&SubTy) const
bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace, Instruction *I=nullptr, int64_t ScalableOffset=0) const override
InstructionCost getScalarizationOverhead(VectorType *InTy, const APInt &DemandedElts, bool Insert, bool Extract, TTI::TargetCostKind CostKind, bool ForPoisonSrc=true, ArrayRef< Value * > VL={}, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind) const override
InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Op1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Op2Info={TTI::OK_AnyValue, TTI::OP_None}, const Instruction *I=nullptr) const override
InstructionCost getCallInstrCost(Function *F, Type *RetTy, ArrayRef< Type * > Tys, TTI::TargetCostKind CostKind) const override
void getUnrollingPreferences(Loop *L, ScalarEvolution &SE, TTI::UnrollingPreferences &UP, OptimizationRemarkEmitter *ORE) const override
void getPeelingPreferences(Loop *L, ScalarEvolution &SE, TTI::PeelingPreferences &PP) const override
InstructionCost getMulAccReductionCost(bool IsUnsigned, unsigned RedOpcode, Type *ResTy, VectorType *Ty, TTI::TargetCostKind CostKind) const override
InstructionCost getShuffleCost(TTI::ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy, TTI::TargetCostKind CostKind, ArrayRef< int > Mask, int Index, VectorType *SubTp, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const override
std::pair< InstructionCost, MVT > getTypeLegalizationCost(Type *Ty) const
InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index, const Value *Op0, const Value *Op1, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const override
InstructionCost getExtendedReductionCost(unsigned Opcode, bool IsUnsigned, Type *ResTy, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind) const override
InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const override
InstructionCost getAddressComputationCost(Type *PtrTy, ScalarEvolution *, const SCEV *, TTI::TargetCostKind) const override
InstructionCost getMemIntrinsicInstrCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind) const override
InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, TTI::OperandValueInfo OpInfo={TTI::OK_AnyValue, TTI::OP_None}, const Instruction *I=nullptr) const override
InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr, ArrayRef< const Value * > Scalars={}) const override
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
This is the shared class of boolean and integer constants.
Definition Constants.h:87
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
This class represents a range of values.
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
Class to represent fixed width SIMD vectors.
unsigned getNumElements() const
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition IRBuilder.h:451
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
The core instruction combiner logic.
const DataLayout & getDataLayout() const
virtual Instruction * eraseInstFromFunction(Instruction &I)=0
Combiner aware instruction erasure.
DominatorTree & getDominatorTree() const
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
virtual bool SimplifyDemandedBits(Instruction *I, unsigned OpNo, const APInt &DemandedMask, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)=0
IRBuilder< TargetFolder, IRBuilderInstCombineInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
AssumptionCache & getAssumptionCache() const
static InstructionCost getInvalid(CostType Val=0)
Instruction * user_back()
user_iterator user_begin()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isShift() const
const SmallVectorImpl< Type * > & getArgTypes() const
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Drive the analysis of memory accesses in the loop.
const PredicatedScalarEvolution & getPSE() const
Used to add runtime SCEV checks.
LoopVectorizationLegality checks if it is legal to vectorize a loop, and to what vectorization factor...
AssumptionCache * getAssumptionCache() const
const LoopAccessInfo * getLAI() const
ScalarEvolution * getScalarEvolution() const
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Information for memory intrinsic cost model.
const Instruction * getInst() const
The optimization diagnostic interface.
An interface layer with SCEV used to manage how we see SCEV expressions for values in the context of ...
ScalarEvolution * getSE() const
Returns the ScalarEvolution analysis used.
This class represents an analyzed expression in the program.
Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
LLVM_ABI const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
LLVM_ABI bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
LLVM_ABI SCEVUse getAddExpr(SmallVectorImpl< SCEVUse > &Ops, SCEVFlagsPair Flags={}, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
LLVM_ABI bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
APInt getUnsignedRangeMax(const SCEV *S)
Determine the max of the unsigned range for a particular SCEV.
static LLVM_ABI bool isDeInterleaveMaskOfFactor(ArrayRef< int > Mask, unsigned Factor, unsigned &Index)
Check if the mask is a DE-interleave mask of the given factor Factor like: <Index,...
static LLVM_ABI bool isInterleaveMask(ArrayRef< int > Mask, unsigned Factor, unsigned NumInputElts, SmallVectorImpl< unsigned > &StartIndexes)
Return true if the mask interleaves one or more input vectors together.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:31
static StackOffset getScalable(int64_t Scalable)
Definition TypeSize.h:41
static StackOffset getFixed(int64_t Fixed)
Definition TypeSize.h:40
Provides information about what library functions are available for the current target.
virtual bool isLoweredToCall(const Function *F) const
bool isConstantStridedAccessLessThan(ScalarEvolution *SE, const SCEV *Ptr, int64_t MergeDistance) const
InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TTI::TargetCostKind CostKind) const override
MaskKind
Some targets only support masked load/store with a constant mask.
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_CodeSize
Instruction code size.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCK_Latency
The latency of instruction.
static bool requiresOrderedReduction(std::optional< FastMathFlags > FMF)
A helper function to determine the type of reduction algorithm used for a given Opcode and set of Fas...
llvm::VectorInstrContext VectorInstrContext
@ TCC_Expensive
The cost of a 'div' instruction on x86.
AddressingModeKind
Which addressing mode Loop Strength Reduction will try to generate.
@ AMK_PostIndexed
Prefer post-indexed addressing mode.
@ AMK_PreIndexed
Prefer pre-indexed addressing mode.
@ AMK_None
Don't prefer any addressing mode.
ShuffleKind
The various kinds of shuffle patterns for vector queries.
@ SK_Select
Selects elements from the corresponding lane of either source operand.
@ SK_PermuteSingleSrc
Shuffle elements of single source vector with any shuffle mask.
@ SK_Broadcast
Broadcast element 0 to all other elements.
@ SK_Reverse
Reverse the order of the vector.
@ SK_ExtractSubvector
ExtractSubvector Index indicates start offset.
CastContextHint
Represents a hint about the context in which a cast is used.
@ Masked
The cast is used with a masked load/store.
@ Normal
The cast is used with a normal load/store.
This class represents a truncation of integer types.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
const Use & getOperandUse(unsigned i) const
Definition User.h:220
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition Value.cpp:142
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
Type * getElementType() const
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
int getSOImmVal(unsigned Arg)
getSOImmVal - Given a 32-bit immediate, if it is something that can fit into an shifter_operand immed...
bool isThumbImmShiftedVal(unsigned V)
isThumbImmShiftedVal - Return true if the specified value can be obtained by left shifting a 8-bit im...
int getT2SOImmVal(unsigned Arg)
getT2SOImmVal - Given a 32-bit immediate, if it is something that can fit into a Thumb-2 shifter_oper...
ISD namespace - This namespace contains an enum which represents all of the SelectionDAG node types a...
Definition ISDOpcodes.h:26
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:912
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:282
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:876
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:828
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:793
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:659
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:882
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:751
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:958
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:763
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:991
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:888
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Constant()
Match an arbitrary Constant and ignore it.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
FNeg_match< OpTy, true > m_FNegOrFSubNegZero(const OpTy &X)
Match fneg X or fsub -0.0, X.
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
auto m_Undef()
Match an arbitrary undef constant.
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
This is an optimization pass for GlobalISel generic memory operations.
bool isVTRN_v_undef_Mask(ArrayRef< int > M, EVT VT, unsigned &WhichResult)
isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of "vector_shuffle v,...
const CostTblEntryT< CostType > * CostTableLookup(ArrayRef< CostTblEntryT< CostType > > Tbl, int ISD, MVT Ty)
Find in cost table.
Definition CostTable.h:36
LLVM_ABI bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name)
Returns true if Name is applied to TheLoop and enabled.
bool isVZIPMask(ArrayRef< int > M, EVT VT, unsigned &WhichResult)
InstructionCost Cost
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Runtime
Detect stack use after return if not disabled runtime with (ASAN_OPTIONS=detect_stack_use_after_retur...
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
LLVM_ABI std::optional< int64_t > getPtrStride(PredicatedScalarEvolution &PSE, Type *AccessTy, Value *Ptr, const Loop *Lp, const DominatorTree &DT, const SymbolicStrideMap &StridesMap=SymbolicStrideMap(), bool ShouldCheckWrap=true, SmallVectorImpl< const SCEVPredicate * > *Predicates=nullptr)
If the pointer has a constant stride return it in units of the access type size.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI SmallVector< Instruction *, 8 > findDefsUsedOutsideOfLoop(Loop *L)
Returns the instructions that use values defined in the loop.
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_ABS
Floating point maxnum.
@ SPF_FMAXNUM
Floating point minnum.
@ SPF_UMIN
Signed minimum.
@ SPF_UMAX
Signed maximum.
@ SPF_SMAX
Unsigned minimum.
@ SPF_FMINNUM
Unsigned maximum.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isVUZPMask(ArrayRef< int > M, EVT VT, unsigned &WhichResult)
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
bool isVTRNMask(ArrayRef< int > M, EVT VT, unsigned &WhichResult)
RecurKind
These are the kinds of recurrences that we support.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
DWARFExpression::Operation Op
bool isVUZP_v_undef_Mask(ArrayRef< int > M, EVT VT, unsigned &WhichResult)
isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of "vector_shuffle v,...
TypeConversionCostTblEntryT< uint16_t > TypeConversionCostTblEntry
Definition CostTable.h:62
CostTblEntryT< uint16_t > CostTblEntry
Definition CostTable.h:31
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Align getKnownAlignment(Value *V, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to infer an alignment for the specified pointer.
Definition Local.h:241
Type * getLoadStoreType(const Value *I)
A helper function that returns the type of a load or store instruction.
bool isVREVMask(ArrayRef< int > M, EVT VT, unsigned BlockSize)
isVREVMask - Check if a vector shuffle corresponds to a VREV instruction with the specified blocksize...
@ DataWithoutLaneMask
Same as Data, but avoids using the get.active.lane.mask intrinsic to calculate the mask and instead i...
@ Data
Use predicate only to mask operations on data in the loop.
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
const TypeConversionCostTblEntryT< CostType > * ConvertCostTableLookup(ArrayRef< TypeConversionCostTblEntryT< CostType > > Tbl, int ISD, MVT Dst, MVT Src)
Find in type conversion cost table.
Definition CostTable.h:67
bool isVZIP_v_undef_Mask(ArrayRef< int > M, EVT VT, unsigned &WhichResult)
isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of "vector_shuffle v,...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
Extended Value Type.
Definition ValueTypes.h:35
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:160
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:170
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:423
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:354
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:361
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:366
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:374
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:175
Attributes of a target dependent hardware loop.
LLVM_ABI bool canAnalyze(LoopInfo &LI)
LLVM_ABI bool isHardwareLoopCandidate(ScalarEvolution &SE, LoopInfo &LI, DominatorTree &DT, bool ForceNestedLoop=false, bool ForceHardwareLoopPHI=false)
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
static MemOp Set(uint64_t Size, bool DstAlignCanChange, Align DstAlign, bool IsZeroMemset, bool IsVolatile)
static MemOp Move(uint64_t Size, bool DstAlignCanChange, Align DstAlign, Align SrcAlign, bool IsVolatile)
SelectPatternFlavor Flavor
TargetLibraryInfo * TLI
LoopVectorizationLegality * LVL
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*...
Parameters that control the generic loop unrolling transformation.
bool UpperBound
Allow using trip count upper bound to unroll loops.
bool Force
Apply loop unroll on any kind of loop (mainly to loops that fail runtime unrolling).
unsigned PartialOptSizeThreshold
The cost threshold for the unrolled loop when optimizing for size, like OptSizeThreshold,...
unsigned DefaultUnrollRuntimeCount
Default unroll count for loops with run-time trip count.
unsigned UnrollAndJamInnerLoopThreshold
Threshold for unroll and jam, for inner loop size.
bool UnrollAndJam
Allow unroll and jam. Used to enable unroll and jam for the target.
bool UnrollRemainder
Allow unrolling of all the iterations of the runtime loop remainder.
bool Runtime
Allow runtime unrolling (unrolling of loops to expand the size of the loop body even when the number ...
bool Partial
Allow partial unrolling (unrolling of loops to expand the size of the loop body, not only to eliminat...
unsigned OptSizeThreshold
The cost threshold for the unrolled loop when optimizing for size (set to UINT_MAX to disable).