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