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