1 //===- HexagonTargetTransformInfo.cpp - Hexagon specific TTI pass ---------===//
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 /// \file
8 /// This file implements a TargetTransformInfo analysis pass specific to the
9 /// Hexagon target machine. It uses the target's detailed information to provide
10 /// more precise answers to certain TTI queries, while letting the target
11 /// independent and default TTI implementations handle the rest.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "HexagonTargetTransformInfo.h"
16 #include "HexagonSubtarget.h"
17 #include "llvm/Analysis/TargetTransformInfo.h"
18 #include "llvm/CodeGen/ValueTypes.h"
19 #include "llvm/IR/InstrTypes.h"
20 #include "llvm/IR/Instructions.h"
21 #include "llvm/IR/User.h"
22 #include "llvm/Support/Casting.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Transforms/Utils/LoopPeel.h"
25 #include "llvm/Transforms/Utils/UnrollLoop.h"
26 
27 using namespace llvm;
28 
29 #define DEBUG_TYPE "hexagontti"
30 
31 static cl::opt<bool> HexagonAutoHVX("hexagon-autohvx", cl::init(false),
32   cl::Hidden, cl::desc("Enable loop vectorizer for HVX"));
33 
34 static cl::opt<bool> EmitLookupTables("hexagon-emit-lookup-tables",
35   cl::init(true), cl::Hidden,
36   cl::desc("Control lookup table emission on Hexagon target"));
37 
38 static cl::opt<bool> HexagonMaskedVMem("hexagon-masked-vmem", cl::init(true),
39   cl::Hidden, cl::desc("Enable masked loads/stores for HVX"));
40 
41 // Constant "cost factor" to make floating point operations more expensive
42 // in terms of vectorization cost. This isn't the best way, but it should
43 // do. Ultimately, the cost should use cycles.
44 static const unsigned FloatFactor = 4;
45 
46 bool HexagonTTIImpl::useHVX() const {
47   return ST.useHVXOps() && HexagonAutoHVX;
48 }
49 
50 unsigned HexagonTTIImpl::getTypeNumElements(Type *Ty) const {
51   if (auto *VTy = dyn_cast<FixedVectorType>(Ty))
52     return VTy->getNumElements();
53   assert((Ty->isIntegerTy() || Ty->isFloatingPointTy()) &&
54          "Expecting scalar type");
55   return 1;
56 }
57 
58 TargetTransformInfo::PopcntSupportKind
59 HexagonTTIImpl::getPopcntSupport(unsigned IntTyWidthInBit) const {
60   // Return fast hardware support as every input < 64 bits will be promoted
61   // to 64 bits.
62   return TargetTransformInfo::PSK_FastHardware;
63 }
64 
65 // The Hexagon target can unroll loops with run-time trip counts.
66 void HexagonTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
67                                              TTI::UnrollingPreferences &UP) {
68   UP.Runtime = UP.Partial = true;
69 }
70 
71 void HexagonTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
72                                            TTI::PeelingPreferences &PP) {
73   BaseT::getPeelingPreferences(L, SE, PP);
74   // Only try to peel innermost loops with small runtime trip counts.
75   if (L && L->isInnermost() && canPeel(L) &&
76       SE.getSmallConstantTripCount(L) == 0 &&
77       SE.getSmallConstantMaxTripCount(L) > 0 &&
78       SE.getSmallConstantMaxTripCount(L) <= 5) {
79     PP.PeelCount = 2;
80   }
81 }
82 
83 TTI::AddressingModeKind
84 HexagonTTIImpl::getPreferredAddressingMode(const Loop *L,
85                                            ScalarEvolution *SE) const {
86   return TTI::AMK_PostIndexed;
87 }
88 
89 /// --- Vector TTI begin ---
90 
91 unsigned HexagonTTIImpl::getNumberOfRegisters(bool Vector) const {
92   if (Vector)
93     return useHVX() ? 32 : 0;
94   return 32;
95 }
96 
97 unsigned HexagonTTIImpl::getMaxInterleaveFactor(unsigned VF) {
98   return useHVX() ? 2 : 1;
99 }
100 
101 TypeSize
102 HexagonTTIImpl::getRegisterBitWidth(TargetTransformInfo::RegisterKind K) const {
103   switch (K) {
104   case TargetTransformInfo::RGK_Scalar:
105     return TypeSize::getFixed(32);
106   case TargetTransformInfo::RGK_FixedWidthVector:
107     return TypeSize::getFixed(getMinVectorRegisterBitWidth());
108   case TargetTransformInfo::RGK_ScalableVector:
109     return TypeSize::getScalable(0);
110   }
111 
112   llvm_unreachable("Unsupported register kind");
113 }
114 
115 unsigned HexagonTTIImpl::getMinVectorRegisterBitWidth() const {
116   return useHVX() ? ST.getVectorLength()*8 : 32;
117 }
118 
119 ElementCount HexagonTTIImpl::getMinimumVF(unsigned ElemWidth,
120                                           bool IsScalable) const {
121   assert(!IsScalable && "Scalable VFs are not supported for Hexagon");
122   return ElementCount::getFixed((8 * ST.getVectorLength()) / ElemWidth);
123 }
124 
125 unsigned HexagonTTIImpl::getScalarizationOverhead(VectorType *Ty,
126                                                   const APInt &DemandedElts,
127                                                   bool Insert, bool Extract) {
128   return BaseT::getScalarizationOverhead(Ty, DemandedElts, Insert, Extract);
129 }
130 
131 unsigned
132 HexagonTTIImpl::getOperandsScalarizationOverhead(ArrayRef<const Value *> Args,
133                                                  ArrayRef<Type *> Tys) {
134   return BaseT::getOperandsScalarizationOverhead(Args, Tys);
135 }
136 
137 unsigned HexagonTTIImpl::getCallInstrCost(Function *F, Type *RetTy,
138       ArrayRef<Type*> Tys, TTI::TargetCostKind CostKind) {
139   return BaseT::getCallInstrCost(F, RetTy, Tys, CostKind);
140 }
141 
142 unsigned
143 HexagonTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
144                                       TTI::TargetCostKind CostKind) {
145   if (ICA.getID() == Intrinsic::bswap) {
146     std::pair<int, MVT> LT = TLI.getTypeLegalizationCost(DL, ICA.getReturnType());
147     return LT.first + 2;
148   }
149   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
150 }
151 
152 unsigned HexagonTTIImpl::getAddressComputationCost(Type *Tp,
153       ScalarEvolution *SE, const SCEV *S) {
154   return 0;
155 }
156 
157 unsigned HexagonTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
158                                          MaybeAlign Alignment,
159                                          unsigned AddressSpace,
160                                          TTI::TargetCostKind CostKind,
161                                          const Instruction *I) {
162   assert(Opcode == Instruction::Load || Opcode == Instruction::Store);
163   // TODO: Handle other cost kinds.
164   if (CostKind != TTI::TCK_RecipThroughput)
165     return 1;
166 
167   if (Opcode == Instruction::Store)
168     return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
169                                   CostKind, I);
170 
171   if (Src->isVectorTy()) {
172     VectorType *VecTy = cast<VectorType>(Src);
173     unsigned VecWidth = VecTy->getPrimitiveSizeInBits().getFixedSize();
174     if (useHVX() && ST.isTypeForHVX(VecTy)) {
175       unsigned RegWidth =
176           getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
177               .getFixedSize();
178       assert(RegWidth && "Non-zero vector register width expected");
179       // Cost of HVX loads.
180       if (VecWidth % RegWidth == 0)
181         return VecWidth / RegWidth;
182       // Cost of constructing HVX vector from scalar loads
183       const Align RegAlign(RegWidth / 8);
184       if (!Alignment || *Alignment > RegAlign)
185         Alignment = RegAlign;
186       assert(Alignment);
187       unsigned AlignWidth = 8 * Alignment->value();
188       unsigned NumLoads = alignTo(VecWidth, AlignWidth) / AlignWidth;
189       return 3 * NumLoads;
190     }
191 
192     // Non-HVX vectors.
193     // Add extra cost for floating point types.
194     unsigned Cost =
195         VecTy->getElementType()->isFloatingPointTy() ? FloatFactor : 1;
196 
197     // At this point unspecified alignment is considered as Align(1).
198     const Align BoundAlignment = std::min(Alignment.valueOrOne(), Align(8));
199     unsigned AlignWidth = 8 * BoundAlignment.value();
200     unsigned NumLoads = alignTo(VecWidth, AlignWidth) / AlignWidth;
201     if (Alignment == Align(4) || Alignment == Align(8))
202       return Cost * NumLoads;
203     // Loads of less than 32 bits will need extra inserts to compose a vector.
204     assert(BoundAlignment <= Align(8));
205     unsigned LogA = Log2(BoundAlignment);
206     return (3 - LogA) * Cost * NumLoads;
207   }
208 
209   return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
210                                 CostKind, I);
211 }
212 
213 unsigned HexagonTTIImpl::getMaskedMemoryOpCost(unsigned Opcode, Type *Src,
214                                                Align Alignment,
215                                                unsigned AddressSpace,
216                                                TTI::TargetCostKind CostKind) {
217   return BaseT::getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
218                                       CostKind);
219 }
220 
221 unsigned HexagonTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp,
222                                         ArrayRef<int> Mask, int Index,
223                                         Type *SubTp) {
224   return 1;
225 }
226 
227 unsigned HexagonTTIImpl::getGatherScatterOpCost(
228     unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask,
229     Align Alignment, TTI::TargetCostKind CostKind, const Instruction *I) {
230   return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
231                                        Alignment, CostKind, I);
232 }
233 
234 unsigned HexagonTTIImpl::getInterleavedMemoryOpCost(
235     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
236     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
237     bool UseMaskForCond, bool UseMaskForGaps) {
238   if (Indices.size() != Factor || UseMaskForCond || UseMaskForGaps)
239     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
240                                              Alignment, AddressSpace,
241                                              CostKind,
242                                              UseMaskForCond, UseMaskForGaps);
243   return getMemoryOpCost(Opcode, VecTy, MaybeAlign(Alignment), AddressSpace,
244                          CostKind);
245 }
246 
247 unsigned HexagonTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
248                                             Type *CondTy,
249                                             CmpInst::Predicate VecPred,
250                                             TTI::TargetCostKind CostKind,
251                                             const Instruction *I) {
252   if (ValTy->isVectorTy() && CostKind == TTI::TCK_RecipThroughput) {
253     std::pair<int, MVT> LT = TLI.getTypeLegalizationCost(DL, ValTy);
254     if (Opcode == Instruction::FCmp)
255       return LT.first + FloatFactor * getTypeNumElements(ValTy);
256   }
257   return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I);
258 }
259 
260 unsigned HexagonTTIImpl::getArithmeticInstrCost(
261     unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
262     TTI::OperandValueKind Opd1Info,
263     TTI::OperandValueKind Opd2Info, TTI::OperandValueProperties Opd1PropInfo,
264     TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args,
265     const Instruction *CxtI) {
266   // TODO: Handle more cost kinds.
267   if (CostKind != TTI::TCK_RecipThroughput)
268     return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
269                                          Opd2Info, Opd1PropInfo,
270                                          Opd2PropInfo, Args, CxtI);
271 
272   if (Ty->isVectorTy()) {
273     std::pair<int, MVT> LT = TLI.getTypeLegalizationCost(DL, Ty);
274     if (LT.second.isFloatingPoint())
275       return LT.first + FloatFactor * getTypeNumElements(Ty);
276   }
277   return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info, Opd2Info,
278                                        Opd1PropInfo, Opd2PropInfo, Args, CxtI);
279 }
280 
281 unsigned HexagonTTIImpl::getCastInstrCost(unsigned Opcode, Type *DstTy,
282                                           Type *SrcTy, TTI::CastContextHint CCH,
283                                           TTI::TargetCostKind CostKind,
284                                           const Instruction *I) {
285   if (SrcTy->isFPOrFPVectorTy() || DstTy->isFPOrFPVectorTy()) {
286     unsigned SrcN = SrcTy->isFPOrFPVectorTy() ? getTypeNumElements(SrcTy) : 0;
287     unsigned DstN = DstTy->isFPOrFPVectorTy() ? getTypeNumElements(DstTy) : 0;
288 
289     std::pair<int, MVT> SrcLT = TLI.getTypeLegalizationCost(DL, SrcTy);
290     std::pair<int, MVT> DstLT = TLI.getTypeLegalizationCost(DL, DstTy);
291     unsigned Cost = std::max(SrcLT.first, DstLT.first) + FloatFactor * (SrcN + DstN);
292     // TODO: Allow non-throughput costs that aren't binary.
293     if (CostKind != TTI::TCK_RecipThroughput)
294       return Cost == 0 ? 0 : 1;
295     return Cost;
296   }
297   return 1;
298 }
299 
300 unsigned HexagonTTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val,
301       unsigned Index) {
302   Type *ElemTy = Val->isVectorTy() ? cast<VectorType>(Val)->getElementType()
303                                    : Val;
304   if (Opcode == Instruction::InsertElement) {
305     // Need two rotations for non-zero index.
306     unsigned Cost = (Index != 0) ? 2 : 0;
307     if (ElemTy->isIntegerTy(32))
308       return Cost;
309     // If it's not a 32-bit value, there will need to be an extract.
310     return Cost + getVectorInstrCost(Instruction::ExtractElement, Val, Index);
311   }
312 
313   if (Opcode == Instruction::ExtractElement)
314     return 2;
315 
316   return 1;
317 }
318 
319 bool HexagonTTIImpl::isLegalMaskedStore(Type *DataType, Align /*Alignment*/) {
320   return HexagonMaskedVMem && ST.isTypeForHVX(DataType);
321 }
322 
323 bool HexagonTTIImpl::isLegalMaskedLoad(Type *DataType, Align /*Alignment*/) {
324   return HexagonMaskedVMem && ST.isTypeForHVX(DataType);
325 }
326 
327 /// --- Vector TTI end ---
328 
329 unsigned HexagonTTIImpl::getPrefetchDistance() const {
330   return ST.getL1PrefetchDistance();
331 }
332 
333 unsigned HexagonTTIImpl::getCacheLineSize() const {
334   return ST.getL1CacheLineSize();
335 }
336 
337 int
338 HexagonTTIImpl::getUserCost(const User *U,
339                             ArrayRef<const Value *> Operands,
340                             TTI::TargetCostKind CostKind) {
341   auto isCastFoldedIntoLoad = [this](const CastInst *CI) -> bool {
342     if (!CI->isIntegerCast())
343       return false;
344     // Only extensions from an integer type shorter than 32-bit to i32
345     // can be folded into the load.
346     const DataLayout &DL = getDataLayout();
347     unsigned SBW = DL.getTypeSizeInBits(CI->getSrcTy());
348     unsigned DBW = DL.getTypeSizeInBits(CI->getDestTy());
349     if (DBW != 32 || SBW >= DBW)
350       return false;
351 
352     const LoadInst *LI = dyn_cast<const LoadInst>(CI->getOperand(0));
353     // Technically, this code could allow multiple uses of the load, and
354     // check if all the uses are the same extension operation, but this
355     // should be sufficient for most cases.
356     return LI && LI->hasOneUse();
357   };
358 
359   if (const CastInst *CI = dyn_cast<const CastInst>(U))
360     if (isCastFoldedIntoLoad(CI))
361       return TargetTransformInfo::TCC_Free;
362   return BaseT::getUserCost(U, Operands, CostKind);
363 }
364 
365 bool HexagonTTIImpl::shouldBuildLookupTables() const {
366   return EmitLookupTables;
367 }
368