1 //===-- RISCVTargetTransformInfo.cpp - RISC-V specific TTI ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "RISCVTargetTransformInfo.h"
10 #include "MCTargetDesc/RISCVMatInt.h"
11 #include "llvm/Analysis/TargetTransformInfo.h"
12 #include "llvm/CodeGen/BasicTTIImpl.h"
13 #include "llvm/CodeGen/TargetLowering.h"
14 #include <cmath>
15 using namespace llvm;
16 
17 #define DEBUG_TYPE "riscvtti"
18 
19 static cl::opt<unsigned> RVVRegisterWidthLMUL(
20     "riscv-v-register-bit-width-lmul",
21     cl::desc(
22         "The LMUL to use for getRegisterBitWidth queries. Affects LMUL used "
23         "by autovectorized code. Fractional LMULs are not supported."),
24     cl::init(1), cl::Hidden);
25 
26 InstructionCost RISCVTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
27                                             TTI::TargetCostKind CostKind) {
28   assert(Ty->isIntegerTy() &&
29          "getIntImmCost can only estimate cost of materialising integers");
30 
31   // We have a Zero register, so 0 is always free.
32   if (Imm == 0)
33     return TTI::TCC_Free;
34 
35   // Otherwise, we check how many instructions it will take to materialise.
36   const DataLayout &DL = getDataLayout();
37   return RISCVMatInt::getIntMatCost(Imm, DL.getTypeSizeInBits(Ty),
38                                     getST()->getFeatureBits());
39 }
40 
41 InstructionCost RISCVTTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
42                                                 const APInt &Imm, Type *Ty,
43                                                 TTI::TargetCostKind CostKind,
44                                                 Instruction *Inst) {
45   assert(Ty->isIntegerTy() &&
46          "getIntImmCost can only estimate cost of materialising integers");
47 
48   // We have a Zero register, so 0 is always free.
49   if (Imm == 0)
50     return TTI::TCC_Free;
51 
52   // Some instructions in RISC-V can take a 12-bit immediate. Some of these are
53   // commutative, in others the immediate comes from a specific argument index.
54   bool Takes12BitImm = false;
55   unsigned ImmArgIdx = ~0U;
56 
57   switch (Opcode) {
58   case Instruction::GetElementPtr:
59     // Never hoist any arguments to a GetElementPtr. CodeGenPrepare will
60     // split up large offsets in GEP into better parts than ConstantHoisting
61     // can.
62     return TTI::TCC_Free;
63   case Instruction::And:
64     // zext.h
65     if (Imm == UINT64_C(0xffff) && ST->hasStdExtZbb())
66       return TTI::TCC_Free;
67     // zext.w
68     if (Imm == UINT64_C(0xffffffff) && ST->hasStdExtZbb())
69       return TTI::TCC_Free;
70     LLVM_FALLTHROUGH;
71   case Instruction::Add:
72   case Instruction::Or:
73   case Instruction::Xor:
74   case Instruction::Mul:
75     Takes12BitImm = true;
76     break;
77   case Instruction::Sub:
78   case Instruction::Shl:
79   case Instruction::LShr:
80   case Instruction::AShr:
81     Takes12BitImm = true;
82     ImmArgIdx = 1;
83     break;
84   default:
85     break;
86   }
87 
88   if (Takes12BitImm) {
89     // Check immediate is the correct argument...
90     if (Instruction::isCommutative(Opcode) || Idx == ImmArgIdx) {
91       // ... and fits into the 12-bit immediate.
92       if (Imm.getMinSignedBits() <= 64 &&
93           getTLI()->isLegalAddImmediate(Imm.getSExtValue())) {
94         return TTI::TCC_Free;
95       }
96     }
97 
98     // Otherwise, use the full materialisation cost.
99     return getIntImmCost(Imm, Ty, CostKind);
100   }
101 
102   // By default, prevent hoisting.
103   return TTI::TCC_Free;
104 }
105 
106 InstructionCost
107 RISCVTTIImpl::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
108                                   const APInt &Imm, Type *Ty,
109                                   TTI::TargetCostKind CostKind) {
110   // Prevent hoisting in unknown cases.
111   return TTI::TCC_Free;
112 }
113 
114 TargetTransformInfo::PopcntSupportKind
115 RISCVTTIImpl::getPopcntSupport(unsigned TyWidth) {
116   assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
117   return ST->hasStdExtZbb() ? TTI::PSK_FastHardware : TTI::PSK_Software;
118 }
119 
120 bool RISCVTTIImpl::shouldExpandReduction(const IntrinsicInst *II) const {
121   // Currently, the ExpandReductions pass can't expand scalable-vector
122   // reductions, but we still request expansion as RVV doesn't support certain
123   // reductions and the SelectionDAG can't legalize them either.
124   switch (II->getIntrinsicID()) {
125   default:
126     return false;
127   // These reductions have no equivalent in RVV
128   case Intrinsic::vector_reduce_mul:
129   case Intrinsic::vector_reduce_fmul:
130     return true;
131   }
132 }
133 
134 Optional<unsigned> RISCVTTIImpl::getMaxVScale() const {
135   if (ST->hasVInstructions())
136     return ST->getRealMaxVLen() / RISCV::RVVBitsPerBlock;
137   return BaseT::getMaxVScale();
138 }
139 
140 Optional<unsigned> RISCVTTIImpl::getVScaleForTuning() const {
141   if (ST->hasVInstructions())
142     return ST->getRealMinVLen() / RISCV::RVVBitsPerBlock;
143   return BaseT::getVScaleForTuning();
144 }
145 
146 TypeSize
147 RISCVTTIImpl::getRegisterBitWidth(TargetTransformInfo::RegisterKind K) const {
148   unsigned LMUL = PowerOf2Floor(
149       std::max<unsigned>(std::min<unsigned>(RVVRegisterWidthLMUL, 8), 1));
150   switch (K) {
151   case TargetTransformInfo::RGK_Scalar:
152     return TypeSize::getFixed(ST->getXLen());
153   case TargetTransformInfo::RGK_FixedWidthVector:
154     return TypeSize::getFixed(
155         ST->useRVVForFixedLengthVectors() ? LMUL * ST->getRealMinVLen() : 0);
156   case TargetTransformInfo::RGK_ScalableVector:
157     return TypeSize::getScalable(
158         ST->hasVInstructions() ? LMUL * RISCV::RVVBitsPerBlock : 0);
159   }
160 
161   llvm_unreachable("Unsupported register kind");
162 }
163 
164 InstructionCost RISCVTTIImpl::getSpliceCost(VectorType *Tp, int Index) {
165   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
166 
167   unsigned Cost = 2; // vslidedown+vslideup.
168   // TODO: LMUL should increase cost.
169   // TODO: Multiplying by LT.first implies this legalizes into multiple copies
170   // of similar code, but I think we expand through memory.
171   return Cost * LT.first;
172 }
173 
174 InstructionCost RISCVTTIImpl::getShuffleCost(TTI::ShuffleKind Kind,
175                                              VectorType *Tp, ArrayRef<int> Mask,
176                                              int Index, VectorType *SubTp,
177                                              ArrayRef<const Value *> Args) {
178   if (isa<ScalableVectorType>(Tp)) {
179     std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
180     switch (Kind) {
181     default:
182       // Fallthrough to generic handling.
183       // TODO: Most of these cases will return getInvalid in generic code, and
184       // must be implemented here.
185       break;
186     case TTI::SK_Broadcast: {
187       return LT.first * 1;
188     }
189     case TTI::SK_Splice:
190       return getSpliceCost(Tp, Index);
191     case TTI::SK_Reverse:
192       // Most of the cost here is producing the vrgather index register
193       // Example sequence:
194       //   csrr a0, vlenb
195       //   srli a0, a0, 3
196       //   addi a0, a0, -1
197       //   vsetvli a1, zero, e8, mf8, ta, mu (ignored)
198       //   vid.v v9
199       //   vrsub.vx v10, v9, a0
200       //   vrgather.vv v9, v8, v10
201       return LT.first * 6;
202     }
203   }
204 
205   return BaseT::getShuffleCost(Kind, Tp, Mask, Index, SubTp);
206 }
207 
208 InstructionCost
209 RISCVTTIImpl::getMaskedMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment,
210                                     unsigned AddressSpace,
211                                     TTI::TargetCostKind CostKind) {
212   if (!isa<ScalableVectorType>(Src))
213     return BaseT::getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
214                                         CostKind);
215 
216   return getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, CostKind);
217 }
218 
219 InstructionCost RISCVTTIImpl::getGatherScatterOpCost(
220     unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask,
221     Align Alignment, TTI::TargetCostKind CostKind, const Instruction *I) {
222   if (CostKind != TTI::TCK_RecipThroughput)
223     return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
224                                          Alignment, CostKind, I);
225 
226   if ((Opcode == Instruction::Load &&
227        !isLegalMaskedGather(DataTy, Align(Alignment))) ||
228       (Opcode == Instruction::Store &&
229        !isLegalMaskedScatter(DataTy, Align(Alignment))))
230     return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
231                                          Alignment, CostKind, I);
232 
233   // Cost is proportional to the number of memory operations implied.  For
234   // scalable vectors, we use an upper bound on that number since we don't
235   // know exactly what VL will be.
236   auto &VTy = *cast<VectorType>(DataTy);
237   InstructionCost MemOpCost = getMemoryOpCost(Opcode, VTy.getElementType(),
238                                               Alignment, 0, CostKind, I);
239   if (isa<ScalableVectorType>(VTy)) {
240     const unsigned EltSize = DL.getTypeSizeInBits(VTy.getElementType());
241     const unsigned MinSize = DL.getTypeSizeInBits(&VTy).getKnownMinValue();
242     const unsigned VectorBitsMax = ST->getRealMaxVLen();
243     const unsigned MaxVLMAX =
244       RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
245     return MaxVLMAX * MemOpCost;
246   }
247   unsigned NumLoads = cast<FixedVectorType>(VTy).getNumElements();
248   return NumLoads * MemOpCost;
249 }
250 
251 InstructionCost
252 RISCVTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
253                                     TTI::TargetCostKind CostKind) {
254   auto *RetTy = ICA.getReturnType();
255   switch (ICA.getID()) {
256   // TODO: add more intrinsic
257   case Intrinsic::experimental_stepvector: {
258     unsigned Cost = 1; // vid
259     auto LT = TLI->getTypeLegalizationCost(DL, RetTy);
260     return Cost + (LT.first - 1);
261   }
262   default:
263     break;
264   }
265   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
266 }
267 
268 InstructionCost RISCVTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst,
269                                                Type *Src,
270                                                TTI::CastContextHint CCH,
271                                                TTI::TargetCostKind CostKind,
272                                                const Instruction *I) {
273   if (isa<VectorType>(Dst) && isa<VectorType>(Src)) {
274     // FIXME: Need to compute legalizing cost for illegal types.
275     if (!isTypeLegal(Src) || !isTypeLegal(Dst))
276       return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
277 
278     // Skip if element size of Dst or Src is bigger than ELEN.
279     if (Src->getScalarSizeInBits() > ST->getELEN() ||
280         Dst->getScalarSizeInBits() > ST->getELEN())
281       return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
282 
283     int ISD = TLI->InstructionOpcodeToISD(Opcode);
284     assert(ISD && "Invalid opcode");
285 
286     // FIXME: Need to consider vsetvli and lmul.
287     int PowDiff = (int)Log2_32(Dst->getScalarSizeInBits()) -
288                   (int)Log2_32(Src->getScalarSizeInBits());
289     switch (ISD) {
290     case ISD::SIGN_EXTEND:
291     case ISD::ZERO_EXTEND:
292       return 1;
293     case ISD::TRUNCATE:
294     case ISD::FP_EXTEND:
295     case ISD::FP_ROUND:
296       // Counts of narrow/widen instructions.
297       return std::abs(PowDiff);
298     case ISD::FP_TO_SINT:
299     case ISD::FP_TO_UINT:
300     case ISD::SINT_TO_FP:
301     case ISD::UINT_TO_FP:
302       if (std::abs(PowDiff) <= 1)
303         return 1;
304       // Backend could lower (v[sz]ext i8 to double) to vfcvt(v[sz]ext.f8 i8),
305       // so it only need two conversion.
306       if (Src->isIntOrIntVectorTy())
307         return 2;
308       // Counts of narrow/widen instructions.
309       return std::abs(PowDiff);
310     }
311   }
312   return BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
313 }
314 
315 InstructionCost
316 RISCVTTIImpl::getMinMaxReductionCost(VectorType *Ty, VectorType *CondTy,
317                                      bool IsUnsigned,
318                                      TTI::TargetCostKind CostKind) {
319   // FIXME: Only supporting fixed vectors for now.
320   if (!isa<FixedVectorType>(Ty))
321     return BaseT::getMinMaxReductionCost(Ty, CondTy, IsUnsigned, CostKind);
322 
323   if (!ST->useRVVForFixedLengthVectors())
324     return BaseT::getMinMaxReductionCost(Ty, CondTy, IsUnsigned, CostKind);
325 
326   // Skip if scalar size of Ty is bigger than ELEN.
327   if (Ty->getScalarSizeInBits() > ST->getELEN())
328     return BaseT::getMinMaxReductionCost(Ty, CondTy, IsUnsigned, CostKind);
329 
330   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
331   if (Ty->getElementType()->isIntegerTy(1))
332     // vcpop sequences, see vreduction-mask.ll.  umax, smin actually only
333     // cost 2, but we don't have enough info here so we slightly over cost.
334     return (LT.first - 1) + 3;
335 
336   // IR Reduction is composed by two vmv and one rvv reduction instruction.
337   InstructionCost BaseCost = 2;
338   unsigned VL = cast<FixedVectorType>(Ty)->getNumElements();
339   return (LT.first - 1) + BaseCost + Log2_32_Ceil(VL);
340 }
341 
342 InstructionCost
343 RISCVTTIImpl::getArithmeticReductionCost(unsigned Opcode, VectorType *Ty,
344                                          Optional<FastMathFlags> FMF,
345                                          TTI::TargetCostKind CostKind) {
346   // FIXME: Only supporting fixed vectors for now.
347   if (!isa<FixedVectorType>(Ty))
348     return BaseT::getArithmeticReductionCost(Opcode, Ty, FMF, CostKind);
349 
350   if (!ST->useRVVForFixedLengthVectors())
351     return BaseT::getArithmeticReductionCost(Opcode, Ty, FMF, CostKind);
352 
353   // Skip if scalar size of Ty is bigger than ELEN.
354   if (Ty->getScalarSizeInBits() > ST->getELEN())
355     return BaseT::getArithmeticReductionCost(Opcode, Ty, FMF, CostKind);
356 
357   int ISD = TLI->InstructionOpcodeToISD(Opcode);
358   assert(ISD && "Invalid opcode");
359 
360   if (ISD != ISD::ADD && ISD != ISD::OR && ISD != ISD::XOR && ISD != ISD::AND &&
361       ISD != ISD::FADD)
362     return BaseT::getArithmeticReductionCost(Opcode, Ty, FMF, CostKind);
363 
364   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
365   if (Ty->getElementType()->isIntegerTy(1))
366     // vcpop sequences, see vreduction-mask.ll
367     return (LT.first - 1) + (ISD == ISD::AND ? 3 : 2);
368 
369   // IR Reduction is composed by two vmv and one rvv reduction instruction.
370   InstructionCost BaseCost = 2;
371   unsigned VL = cast<FixedVectorType>(Ty)->getNumElements();
372   if (TTI::requiresOrderedReduction(FMF))
373     return (LT.first - 1) + BaseCost + VL;
374   return (LT.first - 1) + BaseCost + Log2_32_Ceil(VL);
375 }
376 
377 void RISCVTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
378                                            TTI::UnrollingPreferences &UP,
379                                            OptimizationRemarkEmitter *ORE) {
380   // TODO: More tuning on benchmarks and metrics with changes as needed
381   //       would apply to all settings below to enable performance.
382 
383 
384   if (ST->enableDefaultUnroll())
385     return BasicTTIImplBase::getUnrollingPreferences(L, SE, UP, ORE);
386 
387   // Enable Upper bound unrolling universally, not dependant upon the conditions
388   // below.
389   UP.UpperBound = true;
390 
391   // Disable loop unrolling for Oz and Os.
392   UP.OptSizeThreshold = 0;
393   UP.PartialOptSizeThreshold = 0;
394   if (L->getHeader()->getParent()->hasOptSize())
395     return;
396 
397   SmallVector<BasicBlock *, 4> ExitingBlocks;
398   L->getExitingBlocks(ExitingBlocks);
399   LLVM_DEBUG(dbgs() << "Loop has:\n"
400                     << "Blocks: " << L->getNumBlocks() << "\n"
401                     << "Exit blocks: " << ExitingBlocks.size() << "\n");
402 
403   // Only allow another exit other than the latch. This acts as an early exit
404   // as it mirrors the profitability calculation of the runtime unroller.
405   if (ExitingBlocks.size() > 2)
406     return;
407 
408   // Limit the CFG of the loop body for targets with a branch predictor.
409   // Allowing 4 blocks permits if-then-else diamonds in the body.
410   if (L->getNumBlocks() > 4)
411     return;
412 
413   // Don't unroll vectorized loops, including the remainder loop
414   if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
415     return;
416 
417   // Scan the loop: don't unroll loops with calls as this could prevent
418   // inlining.
419   InstructionCost Cost = 0;
420   for (auto *BB : L->getBlocks()) {
421     for (auto &I : *BB) {
422       // Initial setting - Don't unroll loops containing vectorized
423       // instructions.
424       if (I.getType()->isVectorTy())
425         return;
426 
427       if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
428         if (const Function *F = cast<CallBase>(I).getCalledFunction()) {
429           if (!isLoweredToCall(F))
430             continue;
431         }
432         return;
433       }
434 
435       SmallVector<const Value *> Operands(I.operand_values());
436       Cost +=
437           getUserCost(&I, Operands, TargetTransformInfo::TCK_SizeAndLatency);
438     }
439   }
440 
441   LLVM_DEBUG(dbgs() << "Cost of loop: " << Cost << "\n");
442 
443   UP.Partial = true;
444   UP.Runtime = true;
445   UP.UnrollRemainder = true;
446   UP.UnrollAndJam = true;
447   UP.UnrollAndJamInnerLoopThreshold = 60;
448 
449   // Force unrolling small loops can be very useful because of the branch
450   // taken cost of the backedge.
451   if (Cost < 12)
452     UP.Force = true;
453 }
454 
455 void RISCVTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
456                                          TTI::PeelingPreferences &PP) {
457   BaseT::getPeelingPreferences(L, SE, PP);
458 }
459 
460 unsigned RISCVTTIImpl::getRegUsageForType(Type *Ty) {
461   TypeSize Size = Ty->getPrimitiveSizeInBits();
462   if (Ty->isVectorTy()) {
463     if (Size.isScalable() && ST->hasVInstructions())
464       return divideCeil(Size.getKnownMinValue(), RISCV::RVVBitsPerBlock);
465 
466     if (ST->useRVVForFixedLengthVectors())
467       return divideCeil(Size, ST->getRealMinVLen());
468   }
469 
470   return BaseT::getRegUsageForType(Ty);
471 }
472