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