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