1 //===- llvm/Analysis/TargetTransformInfo.cpp ------------------------------===//
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 "llvm/Analysis/TargetTransformInfo.h"
10 #include "llvm/Analysis/CFG.h"
11 #include "llvm/Analysis/LoopIterator.h"
12 #include "llvm/Analysis/TargetTransformInfoImpl.h"
13 #include "llvm/IR/CFG.h"
14 #include "llvm/IR/DataLayout.h"
15 #include "llvm/IR/Dominators.h"
16 #include "llvm/IR/Instruction.h"
17 #include "llvm/IR/Instructions.h"
18 #include "llvm/IR/IntrinsicInst.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/IR/Operator.h"
21 #include "llvm/IR/PatternMatch.h"
22 #include "llvm/InitializePasses.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include <utility>
26 
27 using namespace llvm;
28 using namespace PatternMatch;
29 
30 #define DEBUG_TYPE "tti"
31 
32 static cl::opt<bool> EnableReduxCost("costmodel-reduxcost", cl::init(false),
33                                      cl::Hidden,
34                                      cl::desc("Recognize reduction patterns."));
35 
36 namespace {
37 /// No-op implementation of the TTI interface using the utility base
38 /// classes.
39 ///
40 /// This is used when no target specific information is available.
41 struct NoTTIImpl : TargetTransformInfoImplCRTPBase<NoTTIImpl> {
42   explicit NoTTIImpl(const DataLayout &DL)
43       : TargetTransformInfoImplCRTPBase<NoTTIImpl>(DL) {}
44 };
45 } // namespace
46 
47 bool HardwareLoopInfo::canAnalyze(LoopInfo &LI) {
48   // If the loop has irreducible control flow, it can not be converted to
49   // Hardware loop.
50   LoopBlocksRPO RPOT(L);
51   RPOT.perform(&LI);
52   if (containsIrreducibleCFG<const BasicBlock *>(RPOT, LI))
53     return false;
54   return true;
55 }
56 
57 IntrinsicCostAttributes::IntrinsicCostAttributes(const IntrinsicInst &I) :
58     II(&I), RetTy(I.getType()), IID(I.getIntrinsicID()) {
59 
60  FunctionType *FTy = I.getCalledFunction()->getFunctionType();
61  ParamTys.insert(ParamTys.begin(), FTy->param_begin(), FTy->param_end());
62  Arguments.insert(Arguments.begin(), I.arg_begin(), I.arg_end());
63  if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
64    FMF = FPMO->getFastMathFlags();
65 }
66 
67 IntrinsicCostAttributes::IntrinsicCostAttributes(Intrinsic::ID Id,
68                                                  const CallBase &CI) :
69   II(dyn_cast<IntrinsicInst>(&CI)),  RetTy(CI.getType()), IID(Id) {
70 
71   if (const auto *FPMO = dyn_cast<FPMathOperator>(&CI))
72     FMF = FPMO->getFastMathFlags();
73 
74   Arguments.insert(Arguments.begin(), CI.arg_begin(), CI.arg_end());
75   FunctionType *FTy =
76     CI.getCalledFunction()->getFunctionType();
77   ParamTys.insert(ParamTys.begin(), FTy->param_begin(), FTy->param_end());
78 }
79 
80 IntrinsicCostAttributes::IntrinsicCostAttributes(Intrinsic::ID Id,
81                                                  const CallBase &CI,
82                                                  ElementCount Factor)
83     : RetTy(CI.getType()), IID(Id), VF(Factor) {
84 
85   assert(!Factor.isScalable() && "Scalable vectors are not yet supported");
86   if (auto *FPMO = dyn_cast<FPMathOperator>(&CI))
87     FMF = FPMO->getFastMathFlags();
88 
89   Arguments.insert(Arguments.begin(), CI.arg_begin(), CI.arg_end());
90   FunctionType *FTy =
91     CI.getCalledFunction()->getFunctionType();
92   ParamTys.insert(ParamTys.begin(), FTy->param_begin(), FTy->param_end());
93 }
94 
95 IntrinsicCostAttributes::IntrinsicCostAttributes(Intrinsic::ID Id,
96                                                  const CallBase &CI,
97                                                  ElementCount Factor,
98                                                  unsigned ScalarCost)
99     : RetTy(CI.getType()), IID(Id), VF(Factor), ScalarizationCost(ScalarCost) {
100 
101   if (const auto *FPMO = dyn_cast<FPMathOperator>(&CI))
102     FMF = FPMO->getFastMathFlags();
103 
104   Arguments.insert(Arguments.begin(), CI.arg_begin(), CI.arg_end());
105   FunctionType *FTy =
106     CI.getCalledFunction()->getFunctionType();
107   ParamTys.insert(ParamTys.begin(), FTy->param_begin(), FTy->param_end());
108 }
109 
110 IntrinsicCostAttributes::IntrinsicCostAttributes(Intrinsic::ID Id, Type *RTy,
111                                                  ArrayRef<Type *> Tys,
112                                                  FastMathFlags Flags) :
113     RetTy(RTy), IID(Id), FMF(Flags) {
114   ParamTys.insert(ParamTys.begin(), Tys.begin(), Tys.end());
115 }
116 
117 IntrinsicCostAttributes::IntrinsicCostAttributes(Intrinsic::ID Id, Type *RTy,
118                                                  ArrayRef<Type *> Tys,
119                                                  FastMathFlags Flags,
120                                                  unsigned ScalarCost) :
121     RetTy(RTy), IID(Id), FMF(Flags), ScalarizationCost(ScalarCost) {
122   ParamTys.insert(ParamTys.begin(), Tys.begin(), Tys.end());
123 }
124 
125 IntrinsicCostAttributes::IntrinsicCostAttributes(Intrinsic::ID Id, Type *RTy,
126                                                  ArrayRef<Type *> Tys,
127                                                  FastMathFlags Flags,
128                                                  unsigned ScalarCost,
129                                                  const IntrinsicInst *I) :
130     II(I), RetTy(RTy), IID(Id), FMF(Flags), ScalarizationCost(ScalarCost) {
131   ParamTys.insert(ParamTys.begin(), Tys.begin(), Tys.end());
132 }
133 
134 IntrinsicCostAttributes::IntrinsicCostAttributes(Intrinsic::ID Id, Type *RTy,
135                                                  ArrayRef<Type *> Tys) :
136     RetTy(RTy), IID(Id) {
137   ParamTys.insert(ParamTys.begin(), Tys.begin(), Tys.end());
138 }
139 
140 IntrinsicCostAttributes::IntrinsicCostAttributes(Intrinsic::ID Id, Type *Ty,
141                                                  ArrayRef<const Value *> Args)
142     : RetTy(Ty), IID(Id) {
143 
144   Arguments.insert(Arguments.begin(), Args.begin(), Args.end());
145   ParamTys.reserve(Arguments.size());
146   for (unsigned Idx = 0, Size = Arguments.size(); Idx != Size; ++Idx)
147     ParamTys.push_back(Arguments[Idx]->getType());
148 }
149 
150 bool HardwareLoopInfo::isHardwareLoopCandidate(ScalarEvolution &SE,
151                                                LoopInfo &LI, DominatorTree &DT,
152                                                bool ForceNestedLoop,
153                                                bool ForceHardwareLoopPHI) {
154   SmallVector<BasicBlock *, 4> ExitingBlocks;
155   L->getExitingBlocks(ExitingBlocks);
156 
157   for (BasicBlock *BB : ExitingBlocks) {
158     // If we pass the updated counter back through a phi, we need to know
159     // which latch the updated value will be coming from.
160     if (!L->isLoopLatch(BB)) {
161       if (ForceHardwareLoopPHI || CounterInReg)
162         continue;
163     }
164 
165     const SCEV *EC = SE.getExitCount(L, BB);
166     if (isa<SCEVCouldNotCompute>(EC))
167       continue;
168     if (const SCEVConstant *ConstEC = dyn_cast<SCEVConstant>(EC)) {
169       if (ConstEC->getValue()->isZero())
170         continue;
171     } else if (!SE.isLoopInvariant(EC, L))
172       continue;
173 
174     if (SE.getTypeSizeInBits(EC->getType()) > CountType->getBitWidth())
175       continue;
176 
177     // If this exiting block is contained in a nested loop, it is not eligible
178     // for insertion of the branch-and-decrement since the inner loop would
179     // end up messing up the value in the CTR.
180     if (!IsNestingLegal && LI.getLoopFor(BB) != L && !ForceNestedLoop)
181       continue;
182 
183     // We now have a loop-invariant count of loop iterations (which is not the
184     // constant zero) for which we know that this loop will not exit via this
185     // existing block.
186 
187     // We need to make sure that this block will run on every loop iteration.
188     // For this to be true, we must dominate all blocks with backedges. Such
189     // blocks are in-loop predecessors to the header block.
190     bool NotAlways = false;
191     for (BasicBlock *Pred : predecessors(L->getHeader())) {
192       if (!L->contains(Pred))
193         continue;
194 
195       if (!DT.dominates(BB, Pred)) {
196         NotAlways = true;
197         break;
198       }
199     }
200 
201     if (NotAlways)
202       continue;
203 
204     // Make sure this blocks ends with a conditional branch.
205     Instruction *TI = BB->getTerminator();
206     if (!TI)
207       continue;
208 
209     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
210       if (!BI->isConditional())
211         continue;
212 
213       ExitBranch = BI;
214     } else
215       continue;
216 
217     // Note that this block may not be the loop latch block, even if the loop
218     // has a latch block.
219     ExitBlock = BB;
220     TripCount = SE.getAddExpr(EC, SE.getOne(EC->getType()));
221 
222     if (!EC->getType()->isPointerTy() && EC->getType() != CountType)
223       TripCount = SE.getZeroExtendExpr(TripCount, CountType);
224 
225     break;
226   }
227 
228   if (!ExitBlock)
229     return false;
230   return true;
231 }
232 
233 TargetTransformInfo::TargetTransformInfo(const DataLayout &DL)
234     : TTIImpl(new Model<NoTTIImpl>(NoTTIImpl(DL))) {}
235 
236 TargetTransformInfo::~TargetTransformInfo() {}
237 
238 TargetTransformInfo::TargetTransformInfo(TargetTransformInfo &&Arg)
239     : TTIImpl(std::move(Arg.TTIImpl)) {}
240 
241 TargetTransformInfo &TargetTransformInfo::operator=(TargetTransformInfo &&RHS) {
242   TTIImpl = std::move(RHS.TTIImpl);
243   return *this;
244 }
245 
246 unsigned TargetTransformInfo::getInliningThresholdMultiplier() const {
247   return TTIImpl->getInliningThresholdMultiplier();
248 }
249 
250 unsigned
251 TargetTransformInfo::adjustInliningThreshold(const CallBase *CB) const {
252   return TTIImpl->adjustInliningThreshold(CB);
253 }
254 
255 int TargetTransformInfo::getInlinerVectorBonusPercent() const {
256   return TTIImpl->getInlinerVectorBonusPercent();
257 }
258 
259 int TargetTransformInfo::getGEPCost(Type *PointeeType, const Value *Ptr,
260                                     ArrayRef<const Value *> Operands,
261                                     TTI::TargetCostKind CostKind) const {
262   return TTIImpl->getGEPCost(PointeeType, Ptr, Operands, CostKind);
263 }
264 
265 unsigned TargetTransformInfo::getEstimatedNumberOfCaseClusters(
266     const SwitchInst &SI, unsigned &JTSize, ProfileSummaryInfo *PSI,
267     BlockFrequencyInfo *BFI) const {
268   return TTIImpl->getEstimatedNumberOfCaseClusters(SI, JTSize, PSI, BFI);
269 }
270 
271 int TargetTransformInfo::getUserCost(const User *U,
272                                      ArrayRef<const Value *> Operands,
273                                      enum TargetCostKind CostKind) const {
274   int Cost = TTIImpl->getUserCost(U, Operands, CostKind);
275   assert((CostKind == TTI::TCK_RecipThroughput || Cost >= 0) &&
276          "TTI should not produce negative costs!");
277   return Cost;
278 }
279 
280 bool TargetTransformInfo::hasBranchDivergence() const {
281   return TTIImpl->hasBranchDivergence();
282 }
283 
284 bool TargetTransformInfo::useGPUDivergenceAnalysis() const {
285   return TTIImpl->useGPUDivergenceAnalysis();
286 }
287 
288 bool TargetTransformInfo::isSourceOfDivergence(const Value *V) const {
289   return TTIImpl->isSourceOfDivergence(V);
290 }
291 
292 bool llvm::TargetTransformInfo::isAlwaysUniform(const Value *V) const {
293   return TTIImpl->isAlwaysUniform(V);
294 }
295 
296 unsigned TargetTransformInfo::getFlatAddressSpace() const {
297   return TTIImpl->getFlatAddressSpace();
298 }
299 
300 bool TargetTransformInfo::collectFlatAddressOperands(
301     SmallVectorImpl<int> &OpIndexes, Intrinsic::ID IID) const {
302   return TTIImpl->collectFlatAddressOperands(OpIndexes, IID);
303 }
304 
305 bool TargetTransformInfo::isNoopAddrSpaceCast(unsigned FromAS,
306                                               unsigned ToAS) const {
307   return TTIImpl->isNoopAddrSpaceCast(FromAS, ToAS);
308 }
309 
310 unsigned TargetTransformInfo::getAssumedAddrSpace(const Value *V) const {
311   return TTIImpl->getAssumedAddrSpace(V);
312 }
313 
314 Value *TargetTransformInfo::rewriteIntrinsicWithAddressSpace(
315     IntrinsicInst *II, Value *OldV, Value *NewV) const {
316   return TTIImpl->rewriteIntrinsicWithAddressSpace(II, OldV, NewV);
317 }
318 
319 bool TargetTransformInfo::isLoweredToCall(const Function *F) const {
320   return TTIImpl->isLoweredToCall(F);
321 }
322 
323 bool TargetTransformInfo::isHardwareLoopProfitable(
324     Loop *L, ScalarEvolution &SE, AssumptionCache &AC,
325     TargetLibraryInfo *LibInfo, HardwareLoopInfo &HWLoopInfo) const {
326   return TTIImpl->isHardwareLoopProfitable(L, SE, AC, LibInfo, HWLoopInfo);
327 }
328 
329 bool TargetTransformInfo::preferPredicateOverEpilogue(
330     Loop *L, LoopInfo *LI, ScalarEvolution &SE, AssumptionCache &AC,
331     TargetLibraryInfo *TLI, DominatorTree *DT,
332     const LoopAccessInfo *LAI) const {
333   return TTIImpl->preferPredicateOverEpilogue(L, LI, SE, AC, TLI, DT, LAI);
334 }
335 
336 bool TargetTransformInfo::emitGetActiveLaneMask() const {
337   return TTIImpl->emitGetActiveLaneMask();
338 }
339 
340 Optional<Instruction *>
341 TargetTransformInfo::instCombineIntrinsic(InstCombiner &IC,
342                                           IntrinsicInst &II) const {
343   return TTIImpl->instCombineIntrinsic(IC, II);
344 }
345 
346 Optional<Value *> TargetTransformInfo::simplifyDemandedUseBitsIntrinsic(
347     InstCombiner &IC, IntrinsicInst &II, APInt DemandedMask, KnownBits &Known,
348     bool &KnownBitsComputed) const {
349   return TTIImpl->simplifyDemandedUseBitsIntrinsic(IC, II, DemandedMask, Known,
350                                                    KnownBitsComputed);
351 }
352 
353 Optional<Value *> TargetTransformInfo::simplifyDemandedVectorEltsIntrinsic(
354     InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts,
355     APInt &UndefElts2, APInt &UndefElts3,
356     std::function<void(Instruction *, unsigned, APInt, APInt &)>
357         SimplifyAndSetOp) const {
358   return TTIImpl->simplifyDemandedVectorEltsIntrinsic(
359       IC, II, DemandedElts, UndefElts, UndefElts2, UndefElts3,
360       SimplifyAndSetOp);
361 }
362 
363 void TargetTransformInfo::getUnrollingPreferences(
364     Loop *L, ScalarEvolution &SE, UnrollingPreferences &UP) const {
365   return TTIImpl->getUnrollingPreferences(L, SE, UP);
366 }
367 
368 void TargetTransformInfo::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
369                                                 PeelingPreferences &PP) const {
370   return TTIImpl->getPeelingPreferences(L, SE, PP);
371 }
372 
373 bool TargetTransformInfo::isLegalAddImmediate(int64_t Imm) const {
374   return TTIImpl->isLegalAddImmediate(Imm);
375 }
376 
377 bool TargetTransformInfo::isLegalICmpImmediate(int64_t Imm) const {
378   return TTIImpl->isLegalICmpImmediate(Imm);
379 }
380 
381 bool TargetTransformInfo::isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV,
382                                                 int64_t BaseOffset,
383                                                 bool HasBaseReg, int64_t Scale,
384                                                 unsigned AddrSpace,
385                                                 Instruction *I) const {
386   return TTIImpl->isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg,
387                                         Scale, AddrSpace, I);
388 }
389 
390 bool TargetTransformInfo::isLSRCostLess(LSRCost &C1, LSRCost &C2) const {
391   return TTIImpl->isLSRCostLess(C1, C2);
392 }
393 
394 bool TargetTransformInfo::isNumRegsMajorCostOfLSR() const {
395   return TTIImpl->isNumRegsMajorCostOfLSR();
396 }
397 
398 bool TargetTransformInfo::isProfitableLSRChainElement(Instruction *I) const {
399   return TTIImpl->isProfitableLSRChainElement(I);
400 }
401 
402 bool TargetTransformInfo::canMacroFuseCmp() const {
403   return TTIImpl->canMacroFuseCmp();
404 }
405 
406 bool TargetTransformInfo::canSaveCmp(Loop *L, BranchInst **BI,
407                                      ScalarEvolution *SE, LoopInfo *LI,
408                                      DominatorTree *DT, AssumptionCache *AC,
409                                      TargetLibraryInfo *LibInfo) const {
410   return TTIImpl->canSaveCmp(L, BI, SE, LI, DT, AC, LibInfo);
411 }
412 
413 bool TargetTransformInfo::shouldFavorPostInc() const {
414   return TTIImpl->shouldFavorPostInc();
415 }
416 
417 bool TargetTransformInfo::shouldFavorBackedgeIndex(const Loop *L) const {
418   return TTIImpl->shouldFavorBackedgeIndex(L);
419 }
420 
421 bool TargetTransformInfo::isLegalMaskedStore(Type *DataType,
422                                              Align Alignment) const {
423   return TTIImpl->isLegalMaskedStore(DataType, Alignment);
424 }
425 
426 bool TargetTransformInfo::isLegalMaskedLoad(Type *DataType,
427                                             Align Alignment) const {
428   return TTIImpl->isLegalMaskedLoad(DataType, Alignment);
429 }
430 
431 bool TargetTransformInfo::isLegalNTStore(Type *DataType,
432                                          Align Alignment) const {
433   return TTIImpl->isLegalNTStore(DataType, Alignment);
434 }
435 
436 bool TargetTransformInfo::isLegalNTLoad(Type *DataType, Align Alignment) const {
437   return TTIImpl->isLegalNTLoad(DataType, Alignment);
438 }
439 
440 bool TargetTransformInfo::isLegalMaskedGather(Type *DataType,
441                                               Align Alignment) const {
442   return TTIImpl->isLegalMaskedGather(DataType, Alignment);
443 }
444 
445 bool TargetTransformInfo::isLegalMaskedScatter(Type *DataType,
446                                                Align Alignment) const {
447   return TTIImpl->isLegalMaskedScatter(DataType, Alignment);
448 }
449 
450 bool TargetTransformInfo::isLegalMaskedCompressStore(Type *DataType) const {
451   return TTIImpl->isLegalMaskedCompressStore(DataType);
452 }
453 
454 bool TargetTransformInfo::isLegalMaskedExpandLoad(Type *DataType) const {
455   return TTIImpl->isLegalMaskedExpandLoad(DataType);
456 }
457 
458 bool TargetTransformInfo::hasDivRemOp(Type *DataType, bool IsSigned) const {
459   return TTIImpl->hasDivRemOp(DataType, IsSigned);
460 }
461 
462 bool TargetTransformInfo::hasVolatileVariant(Instruction *I,
463                                              unsigned AddrSpace) const {
464   return TTIImpl->hasVolatileVariant(I, AddrSpace);
465 }
466 
467 bool TargetTransformInfo::prefersVectorizedAddressing() const {
468   return TTIImpl->prefersVectorizedAddressing();
469 }
470 
471 int TargetTransformInfo::getScalingFactorCost(Type *Ty, GlobalValue *BaseGV,
472                                               int64_t BaseOffset,
473                                               bool HasBaseReg, int64_t Scale,
474                                               unsigned AddrSpace) const {
475   int Cost = TTIImpl->getScalingFactorCost(Ty, BaseGV, BaseOffset, HasBaseReg,
476                                            Scale, AddrSpace);
477   assert(Cost >= 0 && "TTI should not produce negative costs!");
478   return Cost;
479 }
480 
481 bool TargetTransformInfo::LSRWithInstrQueries() const {
482   return TTIImpl->LSRWithInstrQueries();
483 }
484 
485 bool TargetTransformInfo::isTruncateFree(Type *Ty1, Type *Ty2) const {
486   return TTIImpl->isTruncateFree(Ty1, Ty2);
487 }
488 
489 bool TargetTransformInfo::isProfitableToHoist(Instruction *I) const {
490   return TTIImpl->isProfitableToHoist(I);
491 }
492 
493 bool TargetTransformInfo::useAA() const { return TTIImpl->useAA(); }
494 
495 bool TargetTransformInfo::isTypeLegal(Type *Ty) const {
496   return TTIImpl->isTypeLegal(Ty);
497 }
498 
499 unsigned TargetTransformInfo::getRegUsageForType(Type *Ty) const {
500   return TTIImpl->getRegUsageForType(Ty);
501 }
502 
503 bool TargetTransformInfo::shouldBuildLookupTables() const {
504   return TTIImpl->shouldBuildLookupTables();
505 }
506 bool TargetTransformInfo::shouldBuildLookupTablesForConstant(
507     Constant *C) const {
508   return TTIImpl->shouldBuildLookupTablesForConstant(C);
509 }
510 
511 bool TargetTransformInfo::useColdCCForColdCall(Function &F) const {
512   return TTIImpl->useColdCCForColdCall(F);
513 }
514 
515 unsigned
516 TargetTransformInfo::getScalarizationOverhead(VectorType *Ty,
517                                               const APInt &DemandedElts,
518                                               bool Insert, bool Extract) const {
519   return TTIImpl->getScalarizationOverhead(Ty, DemandedElts, Insert, Extract);
520 }
521 
522 unsigned TargetTransformInfo::getOperandsScalarizationOverhead(
523     ArrayRef<const Value *> Args, unsigned VF) const {
524   return TTIImpl->getOperandsScalarizationOverhead(Args, VF);
525 }
526 
527 bool TargetTransformInfo::supportsEfficientVectorElementLoadStore() const {
528   return TTIImpl->supportsEfficientVectorElementLoadStore();
529 }
530 
531 bool TargetTransformInfo::enableAggressiveInterleaving(
532     bool LoopHasReductions) const {
533   return TTIImpl->enableAggressiveInterleaving(LoopHasReductions);
534 }
535 
536 TargetTransformInfo::MemCmpExpansionOptions
537 TargetTransformInfo::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const {
538   return TTIImpl->enableMemCmpExpansion(OptSize, IsZeroCmp);
539 }
540 
541 bool TargetTransformInfo::enableInterleavedAccessVectorization() const {
542   return TTIImpl->enableInterleavedAccessVectorization();
543 }
544 
545 bool TargetTransformInfo::enableMaskedInterleavedAccessVectorization() const {
546   return TTIImpl->enableMaskedInterleavedAccessVectorization();
547 }
548 
549 bool TargetTransformInfo::isFPVectorizationPotentiallyUnsafe() const {
550   return TTIImpl->isFPVectorizationPotentiallyUnsafe();
551 }
552 
553 bool TargetTransformInfo::allowsMisalignedMemoryAccesses(LLVMContext &Context,
554                                                          unsigned BitWidth,
555                                                          unsigned AddressSpace,
556                                                          unsigned Alignment,
557                                                          bool *Fast) const {
558   return TTIImpl->allowsMisalignedMemoryAccesses(Context, BitWidth,
559                                                  AddressSpace, Alignment, Fast);
560 }
561 
562 TargetTransformInfo::PopcntSupportKind
563 TargetTransformInfo::getPopcntSupport(unsigned IntTyWidthInBit) const {
564   return TTIImpl->getPopcntSupport(IntTyWidthInBit);
565 }
566 
567 bool TargetTransformInfo::haveFastSqrt(Type *Ty) const {
568   return TTIImpl->haveFastSqrt(Ty);
569 }
570 
571 bool TargetTransformInfo::isFCmpOrdCheaperThanFCmpZero(Type *Ty) const {
572   return TTIImpl->isFCmpOrdCheaperThanFCmpZero(Ty);
573 }
574 
575 int TargetTransformInfo::getFPOpCost(Type *Ty) const {
576   int Cost = TTIImpl->getFPOpCost(Ty);
577   assert(Cost >= 0 && "TTI should not produce negative costs!");
578   return Cost;
579 }
580 
581 int TargetTransformInfo::getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx,
582                                                const APInt &Imm,
583                                                Type *Ty) const {
584   int Cost = TTIImpl->getIntImmCodeSizeCost(Opcode, Idx, Imm, Ty);
585   assert(Cost >= 0 && "TTI should not produce negative costs!");
586   return Cost;
587 }
588 
589 int TargetTransformInfo::getIntImmCost(const APInt &Imm, Type *Ty,
590                                        TTI::TargetCostKind CostKind) const {
591   int Cost = TTIImpl->getIntImmCost(Imm, Ty, CostKind);
592   assert(Cost >= 0 && "TTI should not produce negative costs!");
593   return Cost;
594 }
595 
596 int TargetTransformInfo::getIntImmCostInst(unsigned Opcode, unsigned Idx,
597                                            const APInt &Imm, Type *Ty,
598                                            TTI::TargetCostKind CostKind,
599                                            Instruction *Inst) const {
600   int Cost = TTIImpl->getIntImmCostInst(Opcode, Idx, Imm, Ty, CostKind, Inst);
601   assert(Cost >= 0 && "TTI should not produce negative costs!");
602   return Cost;
603 }
604 
605 int
606 TargetTransformInfo::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
607                                          const APInt &Imm, Type *Ty,
608                                          TTI::TargetCostKind CostKind) const {
609   int Cost = TTIImpl->getIntImmCostIntrin(IID, Idx, Imm, Ty, CostKind);
610   assert(Cost >= 0 && "TTI should not produce negative costs!");
611   return Cost;
612 }
613 
614 unsigned TargetTransformInfo::getNumberOfRegisters(unsigned ClassID) const {
615   return TTIImpl->getNumberOfRegisters(ClassID);
616 }
617 
618 unsigned TargetTransformInfo::getRegisterClassForType(bool Vector,
619                                                       Type *Ty) const {
620   return TTIImpl->getRegisterClassForType(Vector, Ty);
621 }
622 
623 const char *TargetTransformInfo::getRegisterClassName(unsigned ClassID) const {
624   return TTIImpl->getRegisterClassName(ClassID);
625 }
626 
627 unsigned TargetTransformInfo::getRegisterBitWidth(bool Vector) const {
628   return TTIImpl->getRegisterBitWidth(Vector);
629 }
630 
631 unsigned TargetTransformInfo::getMinVectorRegisterBitWidth() const {
632   return TTIImpl->getMinVectorRegisterBitWidth();
633 }
634 
635 Optional<unsigned> TargetTransformInfo::getMaxVScale() const {
636   return TTIImpl->getMaxVScale();
637 }
638 
639 bool TargetTransformInfo::shouldMaximizeVectorBandwidth(bool OptSize) const {
640   return TTIImpl->shouldMaximizeVectorBandwidth(OptSize);
641 }
642 
643 unsigned TargetTransformInfo::getMinimumVF(unsigned ElemWidth) const {
644   return TTIImpl->getMinimumVF(ElemWidth);
645 }
646 
647 unsigned TargetTransformInfo::getMaximumVF(unsigned ElemWidth,
648                                            unsigned Opcode) const {
649   return TTIImpl->getMaximumVF(ElemWidth, Opcode);
650 }
651 
652 bool TargetTransformInfo::shouldConsiderAddressTypePromotion(
653     const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const {
654   return TTIImpl->shouldConsiderAddressTypePromotion(
655       I, AllowPromotionWithoutCommonHeader);
656 }
657 
658 unsigned TargetTransformInfo::getCacheLineSize() const {
659   return TTIImpl->getCacheLineSize();
660 }
661 
662 llvm::Optional<unsigned>
663 TargetTransformInfo::getCacheSize(CacheLevel Level) const {
664   return TTIImpl->getCacheSize(Level);
665 }
666 
667 llvm::Optional<unsigned>
668 TargetTransformInfo::getCacheAssociativity(CacheLevel Level) const {
669   return TTIImpl->getCacheAssociativity(Level);
670 }
671 
672 unsigned TargetTransformInfo::getPrefetchDistance() const {
673   return TTIImpl->getPrefetchDistance();
674 }
675 
676 unsigned TargetTransformInfo::getMinPrefetchStride(
677     unsigned NumMemAccesses, unsigned NumStridedMemAccesses,
678     unsigned NumPrefetches, bool HasCall) const {
679   return TTIImpl->getMinPrefetchStride(NumMemAccesses, NumStridedMemAccesses,
680                                        NumPrefetches, HasCall);
681 }
682 
683 unsigned TargetTransformInfo::getMaxPrefetchIterationsAhead() const {
684   return TTIImpl->getMaxPrefetchIterationsAhead();
685 }
686 
687 bool TargetTransformInfo::enableWritePrefetching() const {
688   return TTIImpl->enableWritePrefetching();
689 }
690 
691 unsigned TargetTransformInfo::getMaxInterleaveFactor(unsigned VF) const {
692   return TTIImpl->getMaxInterleaveFactor(VF);
693 }
694 
695 TargetTransformInfo::OperandValueKind
696 TargetTransformInfo::getOperandInfo(const Value *V,
697                                     OperandValueProperties &OpProps) {
698   OperandValueKind OpInfo = OK_AnyValue;
699   OpProps = OP_None;
700 
701   if (const auto *CI = dyn_cast<ConstantInt>(V)) {
702     if (CI->getValue().isPowerOf2())
703       OpProps = OP_PowerOf2;
704     return OK_UniformConstantValue;
705   }
706 
707   // A broadcast shuffle creates a uniform value.
708   // TODO: Add support for non-zero index broadcasts.
709   // TODO: Add support for different source vector width.
710   if (const auto *ShuffleInst = dyn_cast<ShuffleVectorInst>(V))
711     if (ShuffleInst->isZeroEltSplat())
712       OpInfo = OK_UniformValue;
713 
714   const Value *Splat = getSplatValue(V);
715 
716   // Check for a splat of a constant or for a non uniform vector of constants
717   // and check if the constant(s) are all powers of two.
718   if (isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) {
719     OpInfo = OK_NonUniformConstantValue;
720     if (Splat) {
721       OpInfo = OK_UniformConstantValue;
722       if (auto *CI = dyn_cast<ConstantInt>(Splat))
723         if (CI->getValue().isPowerOf2())
724           OpProps = OP_PowerOf2;
725     } else if (const auto *CDS = dyn_cast<ConstantDataSequential>(V)) {
726       OpProps = OP_PowerOf2;
727       for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) {
728         if (auto *CI = dyn_cast<ConstantInt>(CDS->getElementAsConstant(I)))
729           if (CI->getValue().isPowerOf2())
730             continue;
731         OpProps = OP_None;
732         break;
733       }
734     }
735   }
736 
737   // Check for a splat of a uniform value. This is not loop aware, so return
738   // true only for the obviously uniform cases (argument, globalvalue)
739   if (Splat && (isa<Argument>(Splat) || isa<GlobalValue>(Splat)))
740     OpInfo = OK_UniformValue;
741 
742   return OpInfo;
743 }
744 
745 int TargetTransformInfo::getArithmeticInstrCost(
746     unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
747     OperandValueKind Opd1Info,
748     OperandValueKind Opd2Info, OperandValueProperties Opd1PropInfo,
749     OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args,
750     const Instruction *CxtI) const {
751   int Cost = TTIImpl->getArithmeticInstrCost(
752       Opcode, Ty, CostKind, Opd1Info, Opd2Info, Opd1PropInfo, Opd2PropInfo,
753       Args, CxtI);
754   assert(Cost >= 0 && "TTI should not produce negative costs!");
755   return Cost;
756 }
757 
758 int TargetTransformInfo::getShuffleCost(ShuffleKind Kind, VectorType *Ty,
759                                         int Index, VectorType *SubTp) const {
760   int Cost = TTIImpl->getShuffleCost(Kind, Ty, Index, SubTp);
761   assert(Cost >= 0 && "TTI should not produce negative costs!");
762   return Cost;
763 }
764 
765 TTI::CastContextHint
766 TargetTransformInfo::getCastContextHint(const Instruction *I) {
767   if (!I)
768     return CastContextHint::None;
769 
770   auto getLoadStoreKind = [](const Value *V, unsigned LdStOp, unsigned MaskedOp,
771                              unsigned GatScatOp) {
772     const Instruction *I = dyn_cast<Instruction>(V);
773     if (!I)
774       return CastContextHint::None;
775 
776     if (I->getOpcode() == LdStOp)
777       return CastContextHint::Normal;
778 
779     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
780       if (II->getIntrinsicID() == MaskedOp)
781         return TTI::CastContextHint::Masked;
782       if (II->getIntrinsicID() == GatScatOp)
783         return TTI::CastContextHint::GatherScatter;
784     }
785 
786     return TTI::CastContextHint::None;
787   };
788 
789   switch (I->getOpcode()) {
790   case Instruction::ZExt:
791   case Instruction::SExt:
792   case Instruction::FPExt:
793     return getLoadStoreKind(I->getOperand(0), Instruction::Load,
794                             Intrinsic::masked_load, Intrinsic::masked_gather);
795   case Instruction::Trunc:
796   case Instruction::FPTrunc:
797     if (I->hasOneUse())
798       return getLoadStoreKind(*I->user_begin(), Instruction::Store,
799                               Intrinsic::masked_store,
800                               Intrinsic::masked_scatter);
801     break;
802   default:
803     return CastContextHint::None;
804   }
805 
806   return TTI::CastContextHint::None;
807 }
808 
809 int TargetTransformInfo::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
810                                           CastContextHint CCH,
811                                           TTI::TargetCostKind CostKind,
812                                           const Instruction *I) const {
813   assert((I == nullptr || I->getOpcode() == Opcode) &&
814          "Opcode should reflect passed instruction.");
815   int Cost = TTIImpl->getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I);
816   assert(Cost >= 0 && "TTI should not produce negative costs!");
817   return Cost;
818 }
819 
820 int TargetTransformInfo::getExtractWithExtendCost(unsigned Opcode, Type *Dst,
821                                                   VectorType *VecTy,
822                                                   unsigned Index) const {
823   int Cost = TTIImpl->getExtractWithExtendCost(Opcode, Dst, VecTy, Index);
824   assert(Cost >= 0 && "TTI should not produce negative costs!");
825   return Cost;
826 }
827 
828 int TargetTransformInfo::getCFInstrCost(unsigned Opcode,
829                                         TTI::TargetCostKind CostKind) const {
830   int Cost = TTIImpl->getCFInstrCost(Opcode, CostKind);
831   assert(Cost >= 0 && "TTI should not produce negative costs!");
832   return Cost;
833 }
834 
835 int TargetTransformInfo::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
836                                             Type *CondTy,
837                                             CmpInst::Predicate VecPred,
838                                             TTI::TargetCostKind CostKind,
839                                             const Instruction *I) const {
840   assert((I == nullptr || I->getOpcode() == Opcode) &&
841          "Opcode should reflect passed instruction.");
842   int Cost =
843       TTIImpl->getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I);
844   assert(Cost >= 0 && "TTI should not produce negative costs!");
845   return Cost;
846 }
847 
848 int TargetTransformInfo::getVectorInstrCost(unsigned Opcode, Type *Val,
849                                             unsigned Index) const {
850   int Cost = TTIImpl->getVectorInstrCost(Opcode, Val, Index);
851   assert(Cost >= 0 && "TTI should not produce negative costs!");
852   return Cost;
853 }
854 
855 int TargetTransformInfo::getMemoryOpCost(unsigned Opcode, Type *Src,
856                                          Align Alignment, unsigned AddressSpace,
857                                          TTI::TargetCostKind CostKind,
858                                          const Instruction *I) const {
859   assert((I == nullptr || I->getOpcode() == Opcode) &&
860          "Opcode should reflect passed instruction.");
861   int Cost = TTIImpl->getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
862                                       CostKind, I);
863   assert(Cost >= 0 && "TTI should not produce negative costs!");
864   return Cost;
865 }
866 
867 int TargetTransformInfo::getMaskedMemoryOpCost(
868     unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace,
869     TTI::TargetCostKind CostKind) const {
870   int Cost =
871       TTIImpl->getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
872                                      CostKind);
873   assert(Cost >= 0 && "TTI should not produce negative costs!");
874   return Cost;
875 }
876 
877 int TargetTransformInfo::getGatherScatterOpCost(
878     unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask,
879     Align Alignment, TTI::TargetCostKind CostKind, const Instruction *I) const {
880   int Cost = TTIImpl->getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
881                                              Alignment, CostKind, I);
882   assert(Cost >= 0 && "TTI should not produce negative costs!");
883   return Cost;
884 }
885 
886 int TargetTransformInfo::getInterleavedMemoryOpCost(
887     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
888     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
889     bool UseMaskForCond, bool UseMaskForGaps) const {
890   int Cost = TTIImpl->getInterleavedMemoryOpCost(
891       Opcode, VecTy, Factor, Indices, Alignment, AddressSpace, CostKind,
892       UseMaskForCond, UseMaskForGaps);
893   assert(Cost >= 0 && "TTI should not produce negative costs!");
894   return Cost;
895 }
896 
897 int
898 TargetTransformInfo::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
899                                            TTI::TargetCostKind CostKind) const {
900   int Cost = TTIImpl->getIntrinsicInstrCost(ICA, CostKind);
901   assert(Cost >= 0 && "TTI should not produce negative costs!");
902   return Cost;
903 }
904 
905 int TargetTransformInfo::getCallInstrCost(Function *F, Type *RetTy,
906                                           ArrayRef<Type *> Tys,
907                                           TTI::TargetCostKind CostKind) const {
908   int Cost = TTIImpl->getCallInstrCost(F, RetTy, Tys, CostKind);
909   assert(Cost >= 0 && "TTI should not produce negative costs!");
910   return Cost;
911 }
912 
913 unsigned TargetTransformInfo::getNumberOfParts(Type *Tp) const {
914   return TTIImpl->getNumberOfParts(Tp);
915 }
916 
917 int TargetTransformInfo::getAddressComputationCost(Type *Tp,
918                                                    ScalarEvolution *SE,
919                                                    const SCEV *Ptr) const {
920   int Cost = TTIImpl->getAddressComputationCost(Tp, SE, Ptr);
921   assert(Cost >= 0 && "TTI should not produce negative costs!");
922   return Cost;
923 }
924 
925 int TargetTransformInfo::getMemcpyCost(const Instruction *I) const {
926   int Cost = TTIImpl->getMemcpyCost(I);
927   assert(Cost >= 0 && "TTI should not produce negative costs!");
928   return Cost;
929 }
930 
931 int TargetTransformInfo::getArithmeticReductionCost(unsigned Opcode,
932                                                     VectorType *Ty,
933                                                     bool IsPairwiseForm,
934                                                     TTI::TargetCostKind CostKind) const {
935   int Cost = TTIImpl->getArithmeticReductionCost(Opcode, Ty, IsPairwiseForm,
936                                                  CostKind);
937   assert(Cost >= 0 && "TTI should not produce negative costs!");
938   return Cost;
939 }
940 
941 int TargetTransformInfo::getMinMaxReductionCost(
942     VectorType *Ty, VectorType *CondTy, bool IsPairwiseForm, bool IsUnsigned,
943     TTI::TargetCostKind CostKind) const {
944   int Cost =
945       TTIImpl->getMinMaxReductionCost(Ty, CondTy, IsPairwiseForm, IsUnsigned,
946                                       CostKind);
947   assert(Cost >= 0 && "TTI should not produce negative costs!");
948   return Cost;
949 }
950 
951 InstructionCost TargetTransformInfo::getExtendedAddReductionCost(
952     bool IsMLA, bool IsUnsigned, Type *ResTy, VectorType *Ty,
953     TTI::TargetCostKind CostKind) const {
954   return TTIImpl->getExtendedAddReductionCost(IsMLA, IsUnsigned, ResTy, Ty,
955                                               CostKind);
956 }
957 
958 unsigned
959 TargetTransformInfo::getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) const {
960   return TTIImpl->getCostOfKeepingLiveOverCall(Tys);
961 }
962 
963 bool TargetTransformInfo::getTgtMemIntrinsic(IntrinsicInst *Inst,
964                                              MemIntrinsicInfo &Info) const {
965   return TTIImpl->getTgtMemIntrinsic(Inst, Info);
966 }
967 
968 unsigned TargetTransformInfo::getAtomicMemIntrinsicMaxElementSize() const {
969   return TTIImpl->getAtomicMemIntrinsicMaxElementSize();
970 }
971 
972 Value *TargetTransformInfo::getOrCreateResultFromMemIntrinsic(
973     IntrinsicInst *Inst, Type *ExpectedType) const {
974   return TTIImpl->getOrCreateResultFromMemIntrinsic(Inst, ExpectedType);
975 }
976 
977 Type *TargetTransformInfo::getMemcpyLoopLoweringType(
978     LLVMContext &Context, Value *Length, unsigned SrcAddrSpace,
979     unsigned DestAddrSpace, unsigned SrcAlign, unsigned DestAlign) const {
980   return TTIImpl->getMemcpyLoopLoweringType(Context, Length, SrcAddrSpace,
981                                             DestAddrSpace, SrcAlign, DestAlign);
982 }
983 
984 void TargetTransformInfo::getMemcpyLoopResidualLoweringType(
985     SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context,
986     unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace,
987     unsigned SrcAlign, unsigned DestAlign) const {
988   TTIImpl->getMemcpyLoopResidualLoweringType(OpsOut, Context, RemainingBytes,
989                                              SrcAddrSpace, DestAddrSpace,
990                                              SrcAlign, DestAlign);
991 }
992 
993 bool TargetTransformInfo::areInlineCompatible(const Function *Caller,
994                                               const Function *Callee) const {
995   return TTIImpl->areInlineCompatible(Caller, Callee);
996 }
997 
998 bool TargetTransformInfo::areFunctionArgsABICompatible(
999     const Function *Caller, const Function *Callee,
1000     SmallPtrSetImpl<Argument *> &Args) const {
1001   return TTIImpl->areFunctionArgsABICompatible(Caller, Callee, Args);
1002 }
1003 
1004 bool TargetTransformInfo::isIndexedLoadLegal(MemIndexedMode Mode,
1005                                              Type *Ty) const {
1006   return TTIImpl->isIndexedLoadLegal(Mode, Ty);
1007 }
1008 
1009 bool TargetTransformInfo::isIndexedStoreLegal(MemIndexedMode Mode,
1010                                               Type *Ty) const {
1011   return TTIImpl->isIndexedStoreLegal(Mode, Ty);
1012 }
1013 
1014 unsigned TargetTransformInfo::getLoadStoreVecRegBitWidth(unsigned AS) const {
1015   return TTIImpl->getLoadStoreVecRegBitWidth(AS);
1016 }
1017 
1018 bool TargetTransformInfo::isLegalToVectorizeLoad(LoadInst *LI) const {
1019   return TTIImpl->isLegalToVectorizeLoad(LI);
1020 }
1021 
1022 bool TargetTransformInfo::isLegalToVectorizeStore(StoreInst *SI) const {
1023   return TTIImpl->isLegalToVectorizeStore(SI);
1024 }
1025 
1026 bool TargetTransformInfo::isLegalToVectorizeLoadChain(
1027     unsigned ChainSizeInBytes, Align Alignment, unsigned AddrSpace) const {
1028   return TTIImpl->isLegalToVectorizeLoadChain(ChainSizeInBytes, Alignment,
1029                                               AddrSpace);
1030 }
1031 
1032 bool TargetTransformInfo::isLegalToVectorizeStoreChain(
1033     unsigned ChainSizeInBytes, Align Alignment, unsigned AddrSpace) const {
1034   return TTIImpl->isLegalToVectorizeStoreChain(ChainSizeInBytes, Alignment,
1035                                                AddrSpace);
1036 }
1037 
1038 unsigned TargetTransformInfo::getLoadVectorFactor(unsigned VF,
1039                                                   unsigned LoadSize,
1040                                                   unsigned ChainSizeInBytes,
1041                                                   VectorType *VecTy) const {
1042   return TTIImpl->getLoadVectorFactor(VF, LoadSize, ChainSizeInBytes, VecTy);
1043 }
1044 
1045 unsigned TargetTransformInfo::getStoreVectorFactor(unsigned VF,
1046                                                    unsigned StoreSize,
1047                                                    unsigned ChainSizeInBytes,
1048                                                    VectorType *VecTy) const {
1049   return TTIImpl->getStoreVectorFactor(VF, StoreSize, ChainSizeInBytes, VecTy);
1050 }
1051 
1052 bool TargetTransformInfo::useReductionIntrinsic(unsigned Opcode, Type *Ty,
1053                                                 ReductionFlags Flags) const {
1054   return TTIImpl->useReductionIntrinsic(Opcode, Ty, Flags);
1055 }
1056 
1057 bool TargetTransformInfo::preferInLoopReduction(unsigned Opcode, Type *Ty,
1058                                                 ReductionFlags Flags) const {
1059   return TTIImpl->preferInLoopReduction(Opcode, Ty, Flags);
1060 }
1061 
1062 bool TargetTransformInfo::preferPredicatedReductionSelect(
1063     unsigned Opcode, Type *Ty, ReductionFlags Flags) const {
1064   return TTIImpl->preferPredicatedReductionSelect(Opcode, Ty, Flags);
1065 }
1066 
1067 bool TargetTransformInfo::shouldExpandReduction(const IntrinsicInst *II) const {
1068   return TTIImpl->shouldExpandReduction(II);
1069 }
1070 
1071 unsigned TargetTransformInfo::getGISelRematGlobalCost() const {
1072   return TTIImpl->getGISelRematGlobalCost();
1073 }
1074 
1075 bool TargetTransformInfo::supportsScalableVectors() const {
1076   return TTIImpl->supportsScalableVectors();
1077 }
1078 
1079 int TargetTransformInfo::getInstructionLatency(const Instruction *I) const {
1080   return TTIImpl->getInstructionLatency(I);
1081 }
1082 
1083 static bool matchPairwiseShuffleMask(ShuffleVectorInst *SI, bool IsLeft,
1084                                      unsigned Level) {
1085   // We don't need a shuffle if we just want to have element 0 in position 0 of
1086   // the vector.
1087   if (!SI && Level == 0 && IsLeft)
1088     return true;
1089   else if (!SI)
1090     return false;
1091 
1092   SmallVector<int, 32> Mask(
1093       cast<FixedVectorType>(SI->getType())->getNumElements(), -1);
1094 
1095   // Build a mask of 0, 2, ... (left) or 1, 3, ... (right) depending on whether
1096   // we look at the left or right side.
1097   for (unsigned i = 0, e = (1 << Level), val = !IsLeft; i != e; ++i, val += 2)
1098     Mask[i] = val;
1099 
1100   ArrayRef<int> ActualMask = SI->getShuffleMask();
1101   return Mask == ActualMask;
1102 }
1103 
1104 static Optional<TTI::ReductionData> getReductionData(Instruction *I) {
1105   Value *L, *R;
1106   if (m_BinOp(m_Value(L), m_Value(R)).match(I))
1107     return TTI::ReductionData(TTI::RK_Arithmetic, I->getOpcode(), L, R);
1108   if (auto *SI = dyn_cast<SelectInst>(I)) {
1109     if (m_SMin(m_Value(L), m_Value(R)).match(SI) ||
1110         m_SMax(m_Value(L), m_Value(R)).match(SI) ||
1111         m_OrdFMin(m_Value(L), m_Value(R)).match(SI) ||
1112         m_OrdFMax(m_Value(L), m_Value(R)).match(SI) ||
1113         m_UnordFMin(m_Value(L), m_Value(R)).match(SI) ||
1114         m_UnordFMax(m_Value(L), m_Value(R)).match(SI)) {
1115       auto *CI = cast<CmpInst>(SI->getCondition());
1116       return TTI::ReductionData(TTI::RK_MinMax, CI->getOpcode(), L, R);
1117     }
1118     if (m_UMin(m_Value(L), m_Value(R)).match(SI) ||
1119         m_UMax(m_Value(L), m_Value(R)).match(SI)) {
1120       auto *CI = cast<CmpInst>(SI->getCondition());
1121       return TTI::ReductionData(TTI::RK_UnsignedMinMax, CI->getOpcode(), L, R);
1122     }
1123   }
1124   return llvm::None;
1125 }
1126 
1127 static TTI::ReductionKind matchPairwiseReductionAtLevel(Instruction *I,
1128                                                         unsigned Level,
1129                                                         unsigned NumLevels) {
1130   // Match one level of pairwise operations.
1131   // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef,
1132   //       <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef>
1133   // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef,
1134   //       <4 x i32> <i32 1, i32 3, i32 undef, i32 undef>
1135   // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1
1136   if (!I)
1137     return TTI::RK_None;
1138 
1139   assert(I->getType()->isVectorTy() && "Expecting a vector type");
1140 
1141   Optional<TTI::ReductionData> RD = getReductionData(I);
1142   if (!RD)
1143     return TTI::RK_None;
1144 
1145   ShuffleVectorInst *LS = dyn_cast<ShuffleVectorInst>(RD->LHS);
1146   if (!LS && Level)
1147     return TTI::RK_None;
1148   ShuffleVectorInst *RS = dyn_cast<ShuffleVectorInst>(RD->RHS);
1149   if (!RS && Level)
1150     return TTI::RK_None;
1151 
1152   // On level 0 we can omit one shufflevector instruction.
1153   if (!Level && !RS && !LS)
1154     return TTI::RK_None;
1155 
1156   // Shuffle inputs must match.
1157   Value *NextLevelOpL = LS ? LS->getOperand(0) : nullptr;
1158   Value *NextLevelOpR = RS ? RS->getOperand(0) : nullptr;
1159   Value *NextLevelOp = nullptr;
1160   if (NextLevelOpR && NextLevelOpL) {
1161     // If we have two shuffles their operands must match.
1162     if (NextLevelOpL != NextLevelOpR)
1163       return TTI::RK_None;
1164 
1165     NextLevelOp = NextLevelOpL;
1166   } else if (Level == 0 && (NextLevelOpR || NextLevelOpL)) {
1167     // On the first level we can omit the shufflevector <0, undef,...>. So the
1168     // input to the other shufflevector <1, undef> must match with one of the
1169     // inputs to the current binary operation.
1170     // Example:
1171     //  %NextLevelOpL = shufflevector %R, <1, undef ...>
1172     //  %BinOp        = fadd          %NextLevelOpL, %R
1173     if (NextLevelOpL && NextLevelOpL != RD->RHS)
1174       return TTI::RK_None;
1175     else if (NextLevelOpR && NextLevelOpR != RD->LHS)
1176       return TTI::RK_None;
1177 
1178     NextLevelOp = NextLevelOpL ? RD->RHS : RD->LHS;
1179   } else
1180     return TTI::RK_None;
1181 
1182   // Check that the next levels binary operation exists and matches with the
1183   // current one.
1184   if (Level + 1 != NumLevels) {
1185     if (!isa<Instruction>(NextLevelOp))
1186       return TTI::RK_None;
1187     Optional<TTI::ReductionData> NextLevelRD =
1188         getReductionData(cast<Instruction>(NextLevelOp));
1189     if (!NextLevelRD || !RD->hasSameData(*NextLevelRD))
1190       return TTI::RK_None;
1191   }
1192 
1193   // Shuffle mask for pairwise operation must match.
1194   if (matchPairwiseShuffleMask(LS, /*IsLeft=*/true, Level)) {
1195     if (!matchPairwiseShuffleMask(RS, /*IsLeft=*/false, Level))
1196       return TTI::RK_None;
1197   } else if (matchPairwiseShuffleMask(RS, /*IsLeft=*/true, Level)) {
1198     if (!matchPairwiseShuffleMask(LS, /*IsLeft=*/false, Level))
1199       return TTI::RK_None;
1200   } else {
1201     return TTI::RK_None;
1202   }
1203 
1204   if (++Level == NumLevels)
1205     return RD->Kind;
1206 
1207   // Match next level.
1208   return matchPairwiseReductionAtLevel(dyn_cast<Instruction>(NextLevelOp), Level,
1209                                        NumLevels);
1210 }
1211 
1212 TTI::ReductionKind TTI::matchPairwiseReduction(
1213   const ExtractElementInst *ReduxRoot, unsigned &Opcode, VectorType *&Ty) {
1214   if (!EnableReduxCost)
1215     return TTI::RK_None;
1216 
1217   // Need to extract the first element.
1218   ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1));
1219   unsigned Idx = ~0u;
1220   if (CI)
1221     Idx = CI->getZExtValue();
1222   if (Idx != 0)
1223     return TTI::RK_None;
1224 
1225   auto *RdxStart = dyn_cast<Instruction>(ReduxRoot->getOperand(0));
1226   if (!RdxStart)
1227     return TTI::RK_None;
1228   Optional<TTI::ReductionData> RD = getReductionData(RdxStart);
1229   if (!RD)
1230     return TTI::RK_None;
1231 
1232   auto *VecTy = cast<FixedVectorType>(RdxStart->getType());
1233   unsigned NumVecElems = VecTy->getNumElements();
1234   if (!isPowerOf2_32(NumVecElems))
1235     return TTI::RK_None;
1236 
1237   // We look for a sequence of shuffle,shuffle,add triples like the following
1238   // that builds a pairwise reduction tree.
1239   //
1240   //  (X0, X1, X2, X3)
1241   //   (X0 + X1, X2 + X3, undef, undef)
1242   //    ((X0 + X1) + (X2 + X3), undef, undef, undef)
1243   //
1244   // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef,
1245   //       <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef>
1246   // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef,
1247   //       <4 x i32> <i32 1, i32 3, i32 undef, i32 undef>
1248   // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1
1249   // %rdx.shuf.1.0 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef,
1250   //       <4 x i32> <i32 0, i32 undef, i32 undef, i32 undef>
1251   // %rdx.shuf.1.1 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef,
1252   //       <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef>
1253   // %bin.rdx8 = fadd <4 x float> %rdx.shuf.1.0, %rdx.shuf.1.1
1254   // %r = extractelement <4 x float> %bin.rdx8, i32 0
1255   if (matchPairwiseReductionAtLevel(RdxStart, 0, Log2_32(NumVecElems)) ==
1256       TTI::RK_None)
1257     return TTI::RK_None;
1258 
1259   Opcode = RD->Opcode;
1260   Ty = VecTy;
1261 
1262   return RD->Kind;
1263 }
1264 
1265 static std::pair<Value *, ShuffleVectorInst *>
1266 getShuffleAndOtherOprd(Value *L, Value *R) {
1267   ShuffleVectorInst *S = nullptr;
1268 
1269   if ((S = dyn_cast<ShuffleVectorInst>(L)))
1270     return std::make_pair(R, S);
1271 
1272   S = dyn_cast<ShuffleVectorInst>(R);
1273   return std::make_pair(L, S);
1274 }
1275 
1276 TTI::ReductionKind TTI::matchVectorSplittingReduction(
1277   const ExtractElementInst *ReduxRoot, unsigned &Opcode, VectorType *&Ty) {
1278 
1279   if (!EnableReduxCost)
1280     return TTI::RK_None;
1281 
1282   // Need to extract the first element.
1283   ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1));
1284   unsigned Idx = ~0u;
1285   if (CI)
1286     Idx = CI->getZExtValue();
1287   if (Idx != 0)
1288     return TTI::RK_None;
1289 
1290   auto *RdxStart = dyn_cast<Instruction>(ReduxRoot->getOperand(0));
1291   if (!RdxStart)
1292     return TTI::RK_None;
1293   Optional<TTI::ReductionData> RD = getReductionData(RdxStart);
1294   if (!RD)
1295     return TTI::RK_None;
1296 
1297   auto *VecTy = cast<FixedVectorType>(ReduxRoot->getOperand(0)->getType());
1298   unsigned NumVecElems = VecTy->getNumElements();
1299   if (!isPowerOf2_32(NumVecElems))
1300     return TTI::RK_None;
1301 
1302   // We look for a sequence of shuffles and adds like the following matching one
1303   // fadd, shuffle vector pair at a time.
1304   //
1305   // %rdx.shuf = shufflevector <4 x float> %rdx, <4 x float> undef,
1306   //                           <4 x i32> <i32 2, i32 3, i32 undef, i32 undef>
1307   // %bin.rdx = fadd <4 x float> %rdx, %rdx.shuf
1308   // %rdx.shuf7 = shufflevector <4 x float> %bin.rdx, <4 x float> undef,
1309   //                          <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef>
1310   // %bin.rdx8 = fadd <4 x float> %bin.rdx, %rdx.shuf7
1311   // %r = extractelement <4 x float> %bin.rdx8, i32 0
1312 
1313   unsigned MaskStart = 1;
1314   Instruction *RdxOp = RdxStart;
1315   SmallVector<int, 32> ShuffleMask(NumVecElems, 0);
1316   unsigned NumVecElemsRemain = NumVecElems;
1317   while (NumVecElemsRemain - 1) {
1318     // Check for the right reduction operation.
1319     if (!RdxOp)
1320       return TTI::RK_None;
1321     Optional<TTI::ReductionData> RDLevel = getReductionData(RdxOp);
1322     if (!RDLevel || !RDLevel->hasSameData(*RD))
1323       return TTI::RK_None;
1324 
1325     Value *NextRdxOp;
1326     ShuffleVectorInst *Shuffle;
1327     std::tie(NextRdxOp, Shuffle) =
1328         getShuffleAndOtherOprd(RDLevel->LHS, RDLevel->RHS);
1329 
1330     // Check the current reduction operation and the shuffle use the same value.
1331     if (Shuffle == nullptr)
1332       return TTI::RK_None;
1333     if (Shuffle->getOperand(0) != NextRdxOp)
1334       return TTI::RK_None;
1335 
1336     // Check that shuffle masks matches.
1337     for (unsigned j = 0; j != MaskStart; ++j)
1338       ShuffleMask[j] = MaskStart + j;
1339     // Fill the rest of the mask with -1 for undef.
1340     std::fill(&ShuffleMask[MaskStart], ShuffleMask.end(), -1);
1341 
1342     ArrayRef<int> Mask = Shuffle->getShuffleMask();
1343     if (ShuffleMask != Mask)
1344       return TTI::RK_None;
1345 
1346     RdxOp = dyn_cast<Instruction>(NextRdxOp);
1347     NumVecElemsRemain /= 2;
1348     MaskStart *= 2;
1349   }
1350 
1351   Opcode = RD->Opcode;
1352   Ty = VecTy;
1353   return RD->Kind;
1354 }
1355 
1356 TTI::ReductionKind
1357 TTI::matchVectorReduction(const ExtractElementInst *Root, unsigned &Opcode,
1358                           VectorType *&Ty, bool &IsPairwise) {
1359   TTI::ReductionKind RdxKind = matchVectorSplittingReduction(Root, Opcode, Ty);
1360   if (RdxKind != TTI::ReductionKind::RK_None) {
1361     IsPairwise = false;
1362     return RdxKind;
1363   }
1364   IsPairwise = true;
1365   return matchPairwiseReduction(Root, Opcode, Ty);
1366 }
1367 
1368 int TargetTransformInfo::getInstructionThroughput(const Instruction *I) const {
1369   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
1370 
1371   switch (I->getOpcode()) {
1372   case Instruction::GetElementPtr:
1373   case Instruction::Ret:
1374   case Instruction::PHI:
1375   case Instruction::Br:
1376   case Instruction::Add:
1377   case Instruction::FAdd:
1378   case Instruction::Sub:
1379   case Instruction::FSub:
1380   case Instruction::Mul:
1381   case Instruction::FMul:
1382   case Instruction::UDiv:
1383   case Instruction::SDiv:
1384   case Instruction::FDiv:
1385   case Instruction::URem:
1386   case Instruction::SRem:
1387   case Instruction::FRem:
1388   case Instruction::Shl:
1389   case Instruction::LShr:
1390   case Instruction::AShr:
1391   case Instruction::And:
1392   case Instruction::Or:
1393   case Instruction::Xor:
1394   case Instruction::FNeg:
1395   case Instruction::Select:
1396   case Instruction::ICmp:
1397   case Instruction::FCmp:
1398   case Instruction::Store:
1399   case Instruction::Load:
1400   case Instruction::ZExt:
1401   case Instruction::SExt:
1402   case Instruction::FPToUI:
1403   case Instruction::FPToSI:
1404   case Instruction::FPExt:
1405   case Instruction::PtrToInt:
1406   case Instruction::IntToPtr:
1407   case Instruction::SIToFP:
1408   case Instruction::UIToFP:
1409   case Instruction::Trunc:
1410   case Instruction::FPTrunc:
1411   case Instruction::BitCast:
1412   case Instruction::AddrSpaceCast:
1413   case Instruction::ExtractElement:
1414   case Instruction::InsertElement:
1415   case Instruction::ExtractValue:
1416   case Instruction::ShuffleVector:
1417   case Instruction::Call:
1418     return getUserCost(I, CostKind);
1419   default:
1420     // We don't have any information on this instruction.
1421     return -1;
1422   }
1423 }
1424 
1425 TargetTransformInfo::Concept::~Concept() {}
1426 
1427 TargetIRAnalysis::TargetIRAnalysis() : TTICallback(&getDefaultTTI) {}
1428 
1429 TargetIRAnalysis::TargetIRAnalysis(
1430     std::function<Result(const Function &)> TTICallback)
1431     : TTICallback(std::move(TTICallback)) {}
1432 
1433 TargetIRAnalysis::Result TargetIRAnalysis::run(const Function &F,
1434                                                FunctionAnalysisManager &) {
1435   return TTICallback(F);
1436 }
1437 
1438 AnalysisKey TargetIRAnalysis::Key;
1439 
1440 TargetIRAnalysis::Result TargetIRAnalysis::getDefaultTTI(const Function &F) {
1441   return Result(F.getParent()->getDataLayout());
1442 }
1443 
1444 // Register the basic pass.
1445 INITIALIZE_PASS(TargetTransformInfoWrapperPass, "tti",
1446                 "Target Transform Information", false, true)
1447 char TargetTransformInfoWrapperPass::ID = 0;
1448 
1449 void TargetTransformInfoWrapperPass::anchor() {}
1450 
1451 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass()
1452     : ImmutablePass(ID) {
1453   initializeTargetTransformInfoWrapperPassPass(
1454       *PassRegistry::getPassRegistry());
1455 }
1456 
1457 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass(
1458     TargetIRAnalysis TIRA)
1459     : ImmutablePass(ID), TIRA(std::move(TIRA)) {
1460   initializeTargetTransformInfoWrapperPassPass(
1461       *PassRegistry::getPassRegistry());
1462 }
1463 
1464 TargetTransformInfo &TargetTransformInfoWrapperPass::getTTI(const Function &F) {
1465   FunctionAnalysisManager DummyFAM;
1466   TTI = TIRA.run(F, DummyFAM);
1467   return *TTI;
1468 }
1469 
1470 ImmutablePass *
1471 llvm::createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA) {
1472   return new TargetTransformInfoWrapperPass(std::move(TIRA));
1473 }
1474