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   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 (const 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<const 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(const Value *V,
637                                     OperandValueProperties &OpProps) {
638   OperandValueKind OpInfo = OK_AnyValue;
639   OpProps = OP_None;
640 
641   if (const auto *CI = dyn_cast<ConstantInt>(V)) {
642     if (CI->getValue().isPowerOf2())
643       OpProps = OP_PowerOf2;
644     return OK_UniformConstantValue;
645   }
646 
647   // A broadcast shuffle creates a uniform value.
648   // TODO: Add support for non-zero index broadcasts.
649   // TODO: Add support for different source vector width.
650   if (const auto *ShuffleInst = dyn_cast<ShuffleVectorInst>(V))
651     if (ShuffleInst->isZeroEltSplat())
652       OpInfo = OK_UniformValue;
653 
654   const Value *Splat = getSplatValue(V);
655 
656   // Check for a splat of a constant or for a non uniform vector of constants
657   // and check if the constant(s) are all powers of two.
658   if (isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) {
659     OpInfo = OK_NonUniformConstantValue;
660     if (Splat) {
661       OpInfo = OK_UniformConstantValue;
662       if (auto *CI = dyn_cast<ConstantInt>(Splat))
663         if (CI->getValue().isPowerOf2())
664           OpProps = OP_PowerOf2;
665     } else if (const auto *CDS = dyn_cast<ConstantDataSequential>(V)) {
666       OpProps = OP_PowerOf2;
667       for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) {
668         if (auto *CI = dyn_cast<ConstantInt>(CDS->getElementAsConstant(I)))
669           if (CI->getValue().isPowerOf2())
670             continue;
671         OpProps = OP_None;
672         break;
673       }
674     }
675   }
676 
677   // Check for a splat of a uniform value. This is not loop aware, so return
678   // true only for the obviously uniform cases (argument, globalvalue)
679   if (Splat && (isa<Argument>(Splat) || isa<GlobalValue>(Splat)))
680     OpInfo = OK_UniformValue;
681 
682   return OpInfo;
683 }
684 
685 int TargetTransformInfo::getArithmeticInstrCost(
686     unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
687     OperandValueKind Opd1Info,
688     OperandValueKind Opd2Info, OperandValueProperties Opd1PropInfo,
689     OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args,
690     const Instruction *CxtI) const {
691   int Cost = TTIImpl->getArithmeticInstrCost(
692       Opcode, Ty, CostKind, Opd1Info, Opd2Info, Opd1PropInfo, Opd2PropInfo,
693       Args, CxtI);
694   assert(Cost >= 0 && "TTI should not produce negative costs!");
695   return Cost;
696 }
697 
698 int TargetTransformInfo::getShuffleCost(ShuffleKind Kind, VectorType *Ty,
699                                         int Index, VectorType *SubTp) const {
700   int Cost = TTIImpl->getShuffleCost(Kind, Ty, Index, SubTp);
701   assert(Cost >= 0 && "TTI should not produce negative costs!");
702   return Cost;
703 }
704 
705 int TargetTransformInfo::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
706                                           TTI::TargetCostKind CostKind,
707                                           const Instruction *I) const {
708   assert((I == nullptr || I->getOpcode() == Opcode) &&
709          "Opcode should reflect passed instruction.");
710   int Cost = TTIImpl->getCastInstrCost(Opcode, Dst, Src, CostKind, I);
711   assert(Cost >= 0 && "TTI should not produce negative costs!");
712   return Cost;
713 }
714 
715 int TargetTransformInfo::getExtractWithExtendCost(unsigned Opcode, Type *Dst,
716                                                   VectorType *VecTy,
717                                                   unsigned Index) const {
718   int Cost = TTIImpl->getExtractWithExtendCost(Opcode, Dst, VecTy, Index);
719   assert(Cost >= 0 && "TTI should not produce negative costs!");
720   return Cost;
721 }
722 
723 int TargetTransformInfo::getCFInstrCost(unsigned Opcode,
724                                         TTI::TargetCostKind CostKind) const {
725   int Cost = TTIImpl->getCFInstrCost(Opcode, CostKind);
726   assert(Cost >= 0 && "TTI should not produce negative costs!");
727   return Cost;
728 }
729 
730 int TargetTransformInfo::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
731                                             Type *CondTy,
732                                             TTI::TargetCostKind CostKind,
733                                             const Instruction *I) const {
734   assert((I == nullptr || I->getOpcode() == Opcode) &&
735          "Opcode should reflect passed instruction.");
736   int Cost = TTIImpl->getCmpSelInstrCost(Opcode, ValTy, CondTy, CostKind, I);
737   assert(Cost >= 0 && "TTI should not produce negative costs!");
738   return Cost;
739 }
740 
741 int TargetTransformInfo::getVectorInstrCost(unsigned Opcode, Type *Val,
742                                             unsigned Index) const {
743   int Cost = TTIImpl->getVectorInstrCost(Opcode, Val, Index);
744   assert(Cost >= 0 && "TTI should not produce negative costs!");
745   return Cost;
746 }
747 
748 int TargetTransformInfo::getMemoryOpCost(unsigned Opcode, Type *Src,
749                                          Align Alignment, unsigned AddressSpace,
750                                          TTI::TargetCostKind CostKind,
751                                          const Instruction *I) const {
752   assert((I == nullptr || I->getOpcode() == Opcode) &&
753          "Opcode should reflect passed instruction.");
754   int Cost = TTIImpl->getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
755                                       CostKind, I);
756   assert(Cost >= 0 && "TTI should not produce negative costs!");
757   return Cost;
758 }
759 
760 int TargetTransformInfo::getMaskedMemoryOpCost(
761     unsigned Opcode, Type *Src, Align Alignment, 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, const Value *Ptr, bool VariableMask,
772     Align Alignment, TTI::TargetCostKind CostKind, const Instruction *I) const {
773   int Cost = TTIImpl->getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
774                                              Alignment, CostKind, I);
775   assert(Cost >= 0 && "TTI should not produce negative costs!");
776   return Cost;
777 }
778 
779 int TargetTransformInfo::getInterleavedMemoryOpCost(
780     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
781     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
782     bool UseMaskForCond, bool UseMaskForGaps) const {
783   int Cost = TTIImpl->getInterleavedMemoryOpCost(
784       Opcode, VecTy, Factor, Indices, Alignment, AddressSpace, CostKind,
785       UseMaskForCond, UseMaskForGaps);
786   assert(Cost >= 0 && "TTI should not produce negative costs!");
787   return Cost;
788 }
789 
790 int
791 TargetTransformInfo::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
792                                            TTI::TargetCostKind CostKind) const {
793   int Cost = TTIImpl->getIntrinsicInstrCost(ICA, CostKind);
794   assert(Cost >= 0 && "TTI should not produce negative costs!");
795   return Cost;
796 }
797 
798 int TargetTransformInfo::getCallInstrCost(Function *F, Type *RetTy,
799                                           ArrayRef<Type *> Tys,
800                                           TTI::TargetCostKind CostKind) const {
801   int Cost = TTIImpl->getCallInstrCost(F, RetTy, Tys, CostKind);
802   assert(Cost >= 0 && "TTI should not produce negative costs!");
803   return Cost;
804 }
805 
806 unsigned TargetTransformInfo::getNumberOfParts(Type *Tp) const {
807   return TTIImpl->getNumberOfParts(Tp);
808 }
809 
810 int TargetTransformInfo::getAddressComputationCost(Type *Tp,
811                                                    ScalarEvolution *SE,
812                                                    const SCEV *Ptr) const {
813   int Cost = TTIImpl->getAddressComputationCost(Tp, SE, Ptr);
814   assert(Cost >= 0 && "TTI should not produce negative costs!");
815   return Cost;
816 }
817 
818 int TargetTransformInfo::getMemcpyCost(const Instruction *I) const {
819   int Cost = TTIImpl->getMemcpyCost(I);
820   assert(Cost >= 0 && "TTI should not produce negative costs!");
821   return Cost;
822 }
823 
824 int TargetTransformInfo::getArithmeticReductionCost(unsigned Opcode,
825                                                     VectorType *Ty,
826                                                     bool IsPairwiseForm,
827                                                     TTI::TargetCostKind CostKind) const {
828   int Cost = TTIImpl->getArithmeticReductionCost(Opcode, Ty, IsPairwiseForm,
829                                                  CostKind);
830   assert(Cost >= 0 && "TTI should not produce negative costs!");
831   return Cost;
832 }
833 
834 int TargetTransformInfo::getMinMaxReductionCost(
835     VectorType *Ty, VectorType *CondTy, bool IsPairwiseForm, bool IsUnsigned,
836     TTI::TargetCostKind CostKind) const {
837   int Cost =
838       TTIImpl->getMinMaxReductionCost(Ty, CondTy, IsPairwiseForm, IsUnsigned,
839                                       CostKind);
840   assert(Cost >= 0 && "TTI should not produce negative costs!");
841   return Cost;
842 }
843 
844 unsigned
845 TargetTransformInfo::getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) const {
846   return TTIImpl->getCostOfKeepingLiveOverCall(Tys);
847 }
848 
849 bool TargetTransformInfo::getTgtMemIntrinsic(IntrinsicInst *Inst,
850                                              MemIntrinsicInfo &Info) const {
851   return TTIImpl->getTgtMemIntrinsic(Inst, Info);
852 }
853 
854 unsigned TargetTransformInfo::getAtomicMemIntrinsicMaxElementSize() const {
855   return TTIImpl->getAtomicMemIntrinsicMaxElementSize();
856 }
857 
858 Value *TargetTransformInfo::getOrCreateResultFromMemIntrinsic(
859     IntrinsicInst *Inst, Type *ExpectedType) const {
860   return TTIImpl->getOrCreateResultFromMemIntrinsic(Inst, ExpectedType);
861 }
862 
863 Type *TargetTransformInfo::getMemcpyLoopLoweringType(
864     LLVMContext &Context, Value *Length, unsigned SrcAddrSpace,
865     unsigned DestAddrSpace, unsigned SrcAlign, unsigned DestAlign) const {
866   return TTIImpl->getMemcpyLoopLoweringType(Context, Length, SrcAddrSpace,
867                                             DestAddrSpace, SrcAlign, DestAlign);
868 }
869 
870 void TargetTransformInfo::getMemcpyLoopResidualLoweringType(
871     SmallVectorImpl<Type *> &OpsOut, LLVMContext &Context,
872     unsigned RemainingBytes, unsigned SrcAddrSpace, unsigned DestAddrSpace,
873     unsigned SrcAlign, unsigned DestAlign) const {
874   TTIImpl->getMemcpyLoopResidualLoweringType(OpsOut, Context, RemainingBytes,
875                                              SrcAddrSpace, DestAddrSpace,
876                                              SrcAlign, DestAlign);
877 }
878 
879 bool TargetTransformInfo::areInlineCompatible(const Function *Caller,
880                                               const Function *Callee) const {
881   return TTIImpl->areInlineCompatible(Caller, Callee);
882 }
883 
884 bool TargetTransformInfo::areFunctionArgsABICompatible(
885     const Function *Caller, const Function *Callee,
886     SmallPtrSetImpl<Argument *> &Args) const {
887   return TTIImpl->areFunctionArgsABICompatible(Caller, Callee, Args);
888 }
889 
890 bool TargetTransformInfo::isIndexedLoadLegal(MemIndexedMode Mode,
891                                              Type *Ty) const {
892   return TTIImpl->isIndexedLoadLegal(Mode, Ty);
893 }
894 
895 bool TargetTransformInfo::isIndexedStoreLegal(MemIndexedMode Mode,
896                                               Type *Ty) const {
897   return TTIImpl->isIndexedStoreLegal(Mode, Ty);
898 }
899 
900 unsigned TargetTransformInfo::getLoadStoreVecRegBitWidth(unsigned AS) const {
901   return TTIImpl->getLoadStoreVecRegBitWidth(AS);
902 }
903 
904 bool TargetTransformInfo::isLegalToVectorizeLoad(LoadInst *LI) const {
905   return TTIImpl->isLegalToVectorizeLoad(LI);
906 }
907 
908 bool TargetTransformInfo::isLegalToVectorizeStore(StoreInst *SI) const {
909   return TTIImpl->isLegalToVectorizeStore(SI);
910 }
911 
912 bool TargetTransformInfo::isLegalToVectorizeLoadChain(
913     unsigned ChainSizeInBytes, Align Alignment, unsigned AddrSpace) const {
914   return TTIImpl->isLegalToVectorizeLoadChain(ChainSizeInBytes, Alignment,
915                                               AddrSpace);
916 }
917 
918 bool TargetTransformInfo::isLegalToVectorizeStoreChain(
919     unsigned ChainSizeInBytes, Align Alignment, unsigned AddrSpace) const {
920   return TTIImpl->isLegalToVectorizeStoreChain(ChainSizeInBytes, Alignment,
921                                                AddrSpace);
922 }
923 
924 unsigned TargetTransformInfo::getLoadVectorFactor(unsigned VF,
925                                                   unsigned LoadSize,
926                                                   unsigned ChainSizeInBytes,
927                                                   VectorType *VecTy) const {
928   return TTIImpl->getLoadVectorFactor(VF, LoadSize, ChainSizeInBytes, VecTy);
929 }
930 
931 unsigned TargetTransformInfo::getStoreVectorFactor(unsigned VF,
932                                                    unsigned StoreSize,
933                                                    unsigned ChainSizeInBytes,
934                                                    VectorType *VecTy) const {
935   return TTIImpl->getStoreVectorFactor(VF, StoreSize, ChainSizeInBytes, VecTy);
936 }
937 
938 bool TargetTransformInfo::useReductionIntrinsic(unsigned Opcode, Type *Ty,
939                                                 ReductionFlags Flags) const {
940   return TTIImpl->useReductionIntrinsic(Opcode, Ty, Flags);
941 }
942 
943 bool TargetTransformInfo::shouldExpandReduction(const IntrinsicInst *II) const {
944   return TTIImpl->shouldExpandReduction(II);
945 }
946 
947 unsigned TargetTransformInfo::getGISelRematGlobalCost() const {
948   return TTIImpl->getGISelRematGlobalCost();
949 }
950 
951 int TargetTransformInfo::getInstructionLatency(const Instruction *I) const {
952   return TTIImpl->getInstructionLatency(I);
953 }
954 
955 static bool matchPairwiseShuffleMask(ShuffleVectorInst *SI, bool IsLeft,
956                                      unsigned Level) {
957   // We don't need a shuffle if we just want to have element 0 in position 0 of
958   // the vector.
959   if (!SI && Level == 0 && IsLeft)
960     return true;
961   else if (!SI)
962     return false;
963 
964   SmallVector<int, 32> Mask(SI->getType()->getNumElements(), -1);
965 
966   // Build a mask of 0, 2, ... (left) or 1, 3, ... (right) depending on whether
967   // we look at the left or right side.
968   for (unsigned i = 0, e = (1 << Level), val = !IsLeft; i != e; ++i, val += 2)
969     Mask[i] = val;
970 
971   ArrayRef<int> ActualMask = SI->getShuffleMask();
972   return Mask == ActualMask;
973 }
974 
975 static Optional<TTI::ReductionData> getReductionData(Instruction *I) {
976   Value *L, *R;
977   if (m_BinOp(m_Value(L), m_Value(R)).match(I))
978     return TTI::ReductionData(TTI::RK_Arithmetic, I->getOpcode(), L, R);
979   if (auto *SI = dyn_cast<SelectInst>(I)) {
980     if (m_SMin(m_Value(L), m_Value(R)).match(SI) ||
981         m_SMax(m_Value(L), m_Value(R)).match(SI) ||
982         m_OrdFMin(m_Value(L), m_Value(R)).match(SI) ||
983         m_OrdFMax(m_Value(L), m_Value(R)).match(SI) ||
984         m_UnordFMin(m_Value(L), m_Value(R)).match(SI) ||
985         m_UnordFMax(m_Value(L), m_Value(R)).match(SI)) {
986       auto *CI = cast<CmpInst>(SI->getCondition());
987       return TTI::ReductionData(TTI::RK_MinMax, CI->getOpcode(), L, R);
988     }
989     if (m_UMin(m_Value(L), m_Value(R)).match(SI) ||
990         m_UMax(m_Value(L), m_Value(R)).match(SI)) {
991       auto *CI = cast<CmpInst>(SI->getCondition());
992       return TTI::ReductionData(TTI::RK_UnsignedMinMax, CI->getOpcode(), L, R);
993     }
994   }
995   return llvm::None;
996 }
997 
998 static TTI::ReductionKind matchPairwiseReductionAtLevel(Instruction *I,
999                                                         unsigned Level,
1000                                                         unsigned NumLevels) {
1001   // Match one level of pairwise operations.
1002   // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef,
1003   //       <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef>
1004   // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef,
1005   //       <4 x i32> <i32 1, i32 3, i32 undef, i32 undef>
1006   // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1
1007   if (!I)
1008     return TTI::RK_None;
1009 
1010   assert(I->getType()->isVectorTy() && "Expecting a vector type");
1011 
1012   Optional<TTI::ReductionData> RD = getReductionData(I);
1013   if (!RD)
1014     return TTI::RK_None;
1015 
1016   ShuffleVectorInst *LS = dyn_cast<ShuffleVectorInst>(RD->LHS);
1017   if (!LS && Level)
1018     return TTI::RK_None;
1019   ShuffleVectorInst *RS = dyn_cast<ShuffleVectorInst>(RD->RHS);
1020   if (!RS && Level)
1021     return TTI::RK_None;
1022 
1023   // On level 0 we can omit one shufflevector instruction.
1024   if (!Level && !RS && !LS)
1025     return TTI::RK_None;
1026 
1027   // Shuffle inputs must match.
1028   Value *NextLevelOpL = LS ? LS->getOperand(0) : nullptr;
1029   Value *NextLevelOpR = RS ? RS->getOperand(0) : nullptr;
1030   Value *NextLevelOp = nullptr;
1031   if (NextLevelOpR && NextLevelOpL) {
1032     // If we have two shuffles their operands must match.
1033     if (NextLevelOpL != NextLevelOpR)
1034       return TTI::RK_None;
1035 
1036     NextLevelOp = NextLevelOpL;
1037   } else if (Level == 0 && (NextLevelOpR || NextLevelOpL)) {
1038     // On the first level we can omit the shufflevector <0, undef,...>. So the
1039     // input to the other shufflevector <1, undef> must match with one of the
1040     // inputs to the current binary operation.
1041     // Example:
1042     //  %NextLevelOpL = shufflevector %R, <1, undef ...>
1043     //  %BinOp        = fadd          %NextLevelOpL, %R
1044     if (NextLevelOpL && NextLevelOpL != RD->RHS)
1045       return TTI::RK_None;
1046     else if (NextLevelOpR && NextLevelOpR != RD->LHS)
1047       return TTI::RK_None;
1048 
1049     NextLevelOp = NextLevelOpL ? RD->RHS : RD->LHS;
1050   } else
1051     return TTI::RK_None;
1052 
1053   // Check that the next levels binary operation exists and matches with the
1054   // current one.
1055   if (Level + 1 != NumLevels) {
1056     Optional<TTI::ReductionData> NextLevelRD =
1057         getReductionData(cast<Instruction>(NextLevelOp));
1058     if (!NextLevelRD || !RD->hasSameData(*NextLevelRD))
1059       return TTI::RK_None;
1060   }
1061 
1062   // Shuffle mask for pairwise operation must match.
1063   if (matchPairwiseShuffleMask(LS, /*IsLeft=*/true, Level)) {
1064     if (!matchPairwiseShuffleMask(RS, /*IsLeft=*/false, Level))
1065       return TTI::RK_None;
1066   } else if (matchPairwiseShuffleMask(RS, /*IsLeft=*/true, Level)) {
1067     if (!matchPairwiseShuffleMask(LS, /*IsLeft=*/false, Level))
1068       return TTI::RK_None;
1069   } else {
1070     return TTI::RK_None;
1071   }
1072 
1073   if (++Level == NumLevels)
1074     return RD->Kind;
1075 
1076   // Match next level.
1077   return matchPairwiseReductionAtLevel(cast<Instruction>(NextLevelOp), Level,
1078                                        NumLevels);
1079 }
1080 
1081 TTI::ReductionKind TTI::matchPairwiseReduction(
1082   const ExtractElementInst *ReduxRoot, unsigned &Opcode, VectorType *&Ty) {
1083   if (!EnableReduxCost)
1084     return TTI::RK_None;
1085 
1086   // Need to extract the first element.
1087   ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1));
1088   unsigned Idx = ~0u;
1089   if (CI)
1090     Idx = CI->getZExtValue();
1091   if (Idx != 0)
1092     return TTI::RK_None;
1093 
1094   auto *RdxStart = dyn_cast<Instruction>(ReduxRoot->getOperand(0));
1095   if (!RdxStart)
1096     return TTI::RK_None;
1097   Optional<TTI::ReductionData> RD = getReductionData(RdxStart);
1098   if (!RD)
1099     return TTI::RK_None;
1100 
1101   auto *VecTy = cast<VectorType>(RdxStart->getType());
1102   unsigned NumVecElems = VecTy->getNumElements();
1103   if (!isPowerOf2_32(NumVecElems))
1104     return TTI::RK_None;
1105 
1106   // We look for a sequence of shuffle,shuffle,add triples like the following
1107   // that builds a pairwise reduction tree.
1108   //
1109   //  (X0, X1, X2, X3)
1110   //   (X0 + X1, X2 + X3, undef, undef)
1111   //    ((X0 + X1) + (X2 + X3), undef, undef, undef)
1112   //
1113   // %rdx.shuf.0.0 = shufflevector <4 x float> %rdx, <4 x float> undef,
1114   //       <4 x i32> <i32 0, i32 2 , i32 undef, i32 undef>
1115   // %rdx.shuf.0.1 = shufflevector <4 x float> %rdx, <4 x float> undef,
1116   //       <4 x i32> <i32 1, i32 3, i32 undef, i32 undef>
1117   // %bin.rdx.0 = fadd <4 x float> %rdx.shuf.0.0, %rdx.shuf.0.1
1118   // %rdx.shuf.1.0 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef,
1119   //       <4 x i32> <i32 0, i32 undef, i32 undef, i32 undef>
1120   // %rdx.shuf.1.1 = shufflevector <4 x float> %bin.rdx.0, <4 x float> undef,
1121   //       <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef>
1122   // %bin.rdx8 = fadd <4 x float> %rdx.shuf.1.0, %rdx.shuf.1.1
1123   // %r = extractelement <4 x float> %bin.rdx8, i32 0
1124   if (matchPairwiseReductionAtLevel(RdxStart, 0, Log2_32(NumVecElems)) ==
1125       TTI::RK_None)
1126     return TTI::RK_None;
1127 
1128   Opcode = RD->Opcode;
1129   Ty = VecTy;
1130 
1131   return RD->Kind;
1132 }
1133 
1134 static std::pair<Value *, ShuffleVectorInst *>
1135 getShuffleAndOtherOprd(Value *L, Value *R) {
1136   ShuffleVectorInst *S = nullptr;
1137 
1138   if ((S = dyn_cast<ShuffleVectorInst>(L)))
1139     return std::make_pair(R, S);
1140 
1141   S = dyn_cast<ShuffleVectorInst>(R);
1142   return std::make_pair(L, S);
1143 }
1144 
1145 TTI::ReductionKind TTI::matchVectorSplittingReduction(
1146   const ExtractElementInst *ReduxRoot, unsigned &Opcode, VectorType *&Ty) {
1147 
1148   if (!EnableReduxCost)
1149     return TTI::RK_None;
1150 
1151   // Need to extract the first element.
1152   ConstantInt *CI = dyn_cast<ConstantInt>(ReduxRoot->getOperand(1));
1153   unsigned Idx = ~0u;
1154   if (CI)
1155     Idx = CI->getZExtValue();
1156   if (Idx != 0)
1157     return TTI::RK_None;
1158 
1159   auto *RdxStart = dyn_cast<Instruction>(ReduxRoot->getOperand(0));
1160   if (!RdxStart)
1161     return TTI::RK_None;
1162   Optional<TTI::ReductionData> RD = getReductionData(RdxStart);
1163   if (!RD)
1164     return TTI::RK_None;
1165 
1166   auto *VecTy = cast<VectorType>(ReduxRoot->getOperand(0)->getType());
1167   unsigned NumVecElems = VecTy->getNumElements();
1168   if (!isPowerOf2_32(NumVecElems))
1169     return TTI::RK_None;
1170 
1171   // We look for a sequence of shuffles and adds like the following matching one
1172   // fadd, shuffle vector pair at a time.
1173   //
1174   // %rdx.shuf = shufflevector <4 x float> %rdx, <4 x float> undef,
1175   //                           <4 x i32> <i32 2, i32 3, i32 undef, i32 undef>
1176   // %bin.rdx = fadd <4 x float> %rdx, %rdx.shuf
1177   // %rdx.shuf7 = shufflevector <4 x float> %bin.rdx, <4 x float> undef,
1178   //                          <4 x i32> <i32 1, i32 undef, i32 undef, i32 undef>
1179   // %bin.rdx8 = fadd <4 x float> %bin.rdx, %rdx.shuf7
1180   // %r = extractelement <4 x float> %bin.rdx8, i32 0
1181 
1182   unsigned MaskStart = 1;
1183   Instruction *RdxOp = RdxStart;
1184   SmallVector<int, 32> ShuffleMask(NumVecElems, 0);
1185   unsigned NumVecElemsRemain = NumVecElems;
1186   while (NumVecElemsRemain - 1) {
1187     // Check for the right reduction operation.
1188     if (!RdxOp)
1189       return TTI::RK_None;
1190     Optional<TTI::ReductionData> RDLevel = getReductionData(RdxOp);
1191     if (!RDLevel || !RDLevel->hasSameData(*RD))
1192       return TTI::RK_None;
1193 
1194     Value *NextRdxOp;
1195     ShuffleVectorInst *Shuffle;
1196     std::tie(NextRdxOp, Shuffle) =
1197         getShuffleAndOtherOprd(RDLevel->LHS, RDLevel->RHS);
1198 
1199     // Check the current reduction operation and the shuffle use the same value.
1200     if (Shuffle == nullptr)
1201       return TTI::RK_None;
1202     if (Shuffle->getOperand(0) != NextRdxOp)
1203       return TTI::RK_None;
1204 
1205     // Check that shuffle masks matches.
1206     for (unsigned j = 0; j != MaskStart; ++j)
1207       ShuffleMask[j] = MaskStart + j;
1208     // Fill the rest of the mask with -1 for undef.
1209     std::fill(&ShuffleMask[MaskStart], ShuffleMask.end(), -1);
1210 
1211     ArrayRef<int> Mask = Shuffle->getShuffleMask();
1212     if (ShuffleMask != Mask)
1213       return TTI::RK_None;
1214 
1215     RdxOp = dyn_cast<Instruction>(NextRdxOp);
1216     NumVecElemsRemain /= 2;
1217     MaskStart *= 2;
1218   }
1219 
1220   Opcode = RD->Opcode;
1221   Ty = VecTy;
1222   return RD->Kind;
1223 }
1224 
1225 int TargetTransformInfo::getInstructionThroughput(const Instruction *I) const {
1226   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
1227 
1228   switch (I->getOpcode()) {
1229   case Instruction::GetElementPtr:
1230   case Instruction::Ret:
1231   case Instruction::PHI:
1232   case Instruction::Br:
1233   case Instruction::Add:
1234   case Instruction::FAdd:
1235   case Instruction::Sub:
1236   case Instruction::FSub:
1237   case Instruction::Mul:
1238   case Instruction::FMul:
1239   case Instruction::UDiv:
1240   case Instruction::SDiv:
1241   case Instruction::FDiv:
1242   case Instruction::URem:
1243   case Instruction::SRem:
1244   case Instruction::FRem:
1245   case Instruction::Shl:
1246   case Instruction::LShr:
1247   case Instruction::AShr:
1248   case Instruction::And:
1249   case Instruction::Or:
1250   case Instruction::Xor:
1251   case Instruction::FNeg:
1252   case Instruction::Select:
1253   case Instruction::ICmp:
1254   case Instruction::FCmp:
1255   case Instruction::Store:
1256   case Instruction::Load:
1257   case Instruction::ZExt:
1258   case Instruction::SExt:
1259   case Instruction::FPToUI:
1260   case Instruction::FPToSI:
1261   case Instruction::FPExt:
1262   case Instruction::PtrToInt:
1263   case Instruction::IntToPtr:
1264   case Instruction::SIToFP:
1265   case Instruction::UIToFP:
1266   case Instruction::Trunc:
1267   case Instruction::FPTrunc:
1268   case Instruction::BitCast:
1269   case Instruction::AddrSpaceCast:
1270   case Instruction::ExtractElement:
1271   case Instruction::InsertElement:
1272   case Instruction::ExtractValue:
1273   case Instruction::ShuffleVector:
1274   case Instruction::Call:
1275     return getUserCost(I, CostKind);
1276   default:
1277     // We don't have any information on this instruction.
1278     return -1;
1279   }
1280 }
1281 
1282 TargetTransformInfo::Concept::~Concept() {}
1283 
1284 TargetIRAnalysis::TargetIRAnalysis() : TTICallback(&getDefaultTTI) {}
1285 
1286 TargetIRAnalysis::TargetIRAnalysis(
1287     std::function<Result(const Function &)> TTICallback)
1288     : TTICallback(std::move(TTICallback)) {}
1289 
1290 TargetIRAnalysis::Result TargetIRAnalysis::run(const Function &F,
1291                                                FunctionAnalysisManager &) {
1292   return TTICallback(F);
1293 }
1294 
1295 AnalysisKey TargetIRAnalysis::Key;
1296 
1297 TargetIRAnalysis::Result TargetIRAnalysis::getDefaultTTI(const Function &F) {
1298   return Result(F.getParent()->getDataLayout());
1299 }
1300 
1301 // Register the basic pass.
1302 INITIALIZE_PASS(TargetTransformInfoWrapperPass, "tti",
1303                 "Target Transform Information", false, true)
1304 char TargetTransformInfoWrapperPass::ID = 0;
1305 
1306 void TargetTransformInfoWrapperPass::anchor() {}
1307 
1308 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass()
1309     : ImmutablePass(ID) {
1310   initializeTargetTransformInfoWrapperPassPass(
1311       *PassRegistry::getPassRegistry());
1312 }
1313 
1314 TargetTransformInfoWrapperPass::TargetTransformInfoWrapperPass(
1315     TargetIRAnalysis TIRA)
1316     : ImmutablePass(ID), TIRA(std::move(TIRA)) {
1317   initializeTargetTransformInfoWrapperPassPass(
1318       *PassRegistry::getPassRegistry());
1319 }
1320 
1321 TargetTransformInfo &TargetTransformInfoWrapperPass::getTTI(const Function &F) {
1322   FunctionAnalysisManager DummyFAM;
1323   TTI = TIRA.run(F, DummyFAM);
1324   return *TTI;
1325 }
1326 
1327 ImmutablePass *
1328 llvm::createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA) {
1329   return new TargetTransformInfoWrapperPass(std::move(TIRA));
1330 }
1331