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