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