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