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