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