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