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