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