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