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