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