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