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