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