1 //===-- X86TargetTransformInfo.cpp - X86 specific TTI pass ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This file implements a TargetTransformInfo analysis pass specific to the
10 /// X86 target machine. It uses the target's detailed information to provide
11 /// more precise answers to certain TTI queries, while letting the target
12 /// independent and default TTI implementations handle the rest.
13 ///
14 //===----------------------------------------------------------------------===//
15 /// About Cost Model numbers used below it's necessary to say the following:
16 /// the numbers correspond to some "generic" X86 CPU instead of usage of
17 /// concrete CPU model. Usually the numbers correspond to CPU where the feature
18 /// apeared at the first time. For example, if we do Subtarget.hasSSE42() in
19 /// the lookups below the cost is based on Nehalem as that was the first CPU
20 /// to support that feature level and thus has most likely the worst case cost.
21 /// Some examples of other technologies/CPUs:
22 ///   SSE 3   - Pentium4 / Athlon64
23 ///   SSE 4.1 - Penryn
24 ///   SSE 4.2 - Nehalem
25 ///   AVX     - Sandy Bridge
26 ///   AVX2    - Haswell
27 ///   AVX-512 - Xeon Phi / Skylake
28 /// And some examples of instruction target dependent costs (latency)
29 ///                   divss     sqrtss          rsqrtss
30 ///   AMD K7            11-16     19              3
31 ///   Piledriver        9-24      13-15           5
32 ///   Jaguar            14        16              2
33 ///   Pentium II,III    18        30              2
34 ///   Nehalem           7-14      7-18            3
35 ///   Haswell           10-13     11              5
36 /// TODO: Develop and implement  the target dependent cost model and
37 /// specialize cost numbers for different Cost Model Targets such as throughput,
38 /// code size, latency and uop count.
39 //===----------------------------------------------------------------------===//
40 
41 #include "X86TargetTransformInfo.h"
42 #include "llvm/Analysis/TargetTransformInfo.h"
43 #include "llvm/CodeGen/BasicTTIImpl.h"
44 #include "llvm/CodeGen/CostTable.h"
45 #include "llvm/CodeGen/TargetLowering.h"
46 #include "llvm/IR/IntrinsicInst.h"
47 #include "llvm/Support/Debug.h"
48 
49 using namespace llvm;
50 
51 #define DEBUG_TYPE "x86tti"
52 
53 //===----------------------------------------------------------------------===//
54 //
55 // X86 cost model.
56 //
57 //===----------------------------------------------------------------------===//
58 
59 TargetTransformInfo::PopcntSupportKind
60 X86TTIImpl::getPopcntSupport(unsigned TyWidth) {
61   assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
62   // TODO: Currently the __builtin_popcount() implementation using SSE3
63   //   instructions is inefficient. Once the problem is fixed, we should
64   //   call ST->hasSSE3() instead of ST->hasPOPCNT().
65   return ST->hasPOPCNT() ? TTI::PSK_FastHardware : TTI::PSK_Software;
66 }
67 
68 llvm::Optional<unsigned> X86TTIImpl::getCacheSize(
69   TargetTransformInfo::CacheLevel Level) const {
70   switch (Level) {
71   case TargetTransformInfo::CacheLevel::L1D:
72     //   - Penryn
73     //   - Nehalem
74     //   - Westmere
75     //   - Sandy Bridge
76     //   - Ivy Bridge
77     //   - Haswell
78     //   - Broadwell
79     //   - Skylake
80     //   - Kabylake
81     return 32 * 1024;  //  32 KByte
82   case TargetTransformInfo::CacheLevel::L2D:
83     //   - Penryn
84     //   - Nehalem
85     //   - Westmere
86     //   - Sandy Bridge
87     //   - Ivy Bridge
88     //   - Haswell
89     //   - Broadwell
90     //   - Skylake
91     //   - Kabylake
92     return 256 * 1024; // 256 KByte
93   }
94 
95   llvm_unreachable("Unknown TargetTransformInfo::CacheLevel");
96 }
97 
98 llvm::Optional<unsigned> X86TTIImpl::getCacheAssociativity(
99   TargetTransformInfo::CacheLevel Level) const {
100   //   - Penryn
101   //   - Nehalem
102   //   - Westmere
103   //   - Sandy Bridge
104   //   - Ivy Bridge
105   //   - Haswell
106   //   - Broadwell
107   //   - Skylake
108   //   - Kabylake
109   switch (Level) {
110   case TargetTransformInfo::CacheLevel::L1D:
111     LLVM_FALLTHROUGH;
112   case TargetTransformInfo::CacheLevel::L2D:
113     return 8;
114   }
115 
116   llvm_unreachable("Unknown TargetTransformInfo::CacheLevel");
117 }
118 
119 unsigned X86TTIImpl::getNumberOfRegisters(unsigned ClassID) const {
120   bool Vector = (ClassID == 1);
121   if (Vector && !ST->hasSSE1())
122     return 0;
123 
124   if (ST->is64Bit()) {
125     if (Vector && ST->hasAVX512())
126       return 32;
127     return 16;
128   }
129   return 8;
130 }
131 
132 TypeSize
133 X86TTIImpl::getRegisterBitWidth(TargetTransformInfo::RegisterKind K) const {
134   unsigned PreferVectorWidth = ST->getPreferVectorWidth();
135   switch (K) {
136   case TargetTransformInfo::RGK_Scalar:
137     return TypeSize::getFixed(ST->is64Bit() ? 64 : 32);
138   case TargetTransformInfo::RGK_FixedWidthVector:
139     if (ST->hasAVX512() && PreferVectorWidth >= 512)
140       return TypeSize::getFixed(512);
141     if (ST->hasAVX() && PreferVectorWidth >= 256)
142       return TypeSize::getFixed(256);
143     if (ST->hasSSE1() && PreferVectorWidth >= 128)
144       return TypeSize::getFixed(128);
145     return TypeSize::getFixed(0);
146   case TargetTransformInfo::RGK_ScalableVector:
147     return TypeSize::getScalable(0);
148   }
149 
150   llvm_unreachable("Unsupported register kind");
151 }
152 
153 unsigned X86TTIImpl::getLoadStoreVecRegBitWidth(unsigned) const {
154   return getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
155       .getFixedSize();
156 }
157 
158 unsigned X86TTIImpl::getMaxInterleaveFactor(unsigned VF) {
159   // If the loop will not be vectorized, don't interleave the loop.
160   // Let regular unroll to unroll the loop, which saves the overflow
161   // check and memory check cost.
162   if (VF == 1)
163     return 1;
164 
165   if (ST->isAtom())
166     return 1;
167 
168   // Sandybridge and Haswell have multiple execution ports and pipelined
169   // vector units.
170   if (ST->hasAVX())
171     return 4;
172 
173   return 2;
174 }
175 
176 InstructionCost X86TTIImpl::getArithmeticInstrCost(
177     unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
178     TTI::OperandValueKind Op1Info, TTI::OperandValueKind Op2Info,
179     TTI::OperandValueProperties Opd1PropInfo,
180     TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args,
181     const Instruction *CxtI) {
182   // TODO: Handle more cost kinds.
183   if (CostKind != TTI::TCK_RecipThroughput)
184     return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
185                                          Op2Info, Opd1PropInfo,
186                                          Opd2PropInfo, Args, CxtI);
187 
188   // vXi8 multiplications are always promoted to vXi16.
189   if (Opcode == Instruction::Mul && Ty->isVectorTy() &&
190       Ty->getScalarSizeInBits() == 8) {
191     Type *WideVecTy =
192         VectorType::getExtendedElementVectorType(cast<VectorType>(Ty));
193     return getCastInstrCost(Instruction::ZExt, WideVecTy, Ty,
194                             TargetTransformInfo::CastContextHint::None,
195                             CostKind) +
196            getCastInstrCost(Instruction::Trunc, Ty, WideVecTy,
197                             TargetTransformInfo::CastContextHint::None,
198                             CostKind) +
199            getArithmeticInstrCost(Opcode, WideVecTy, CostKind, Op1Info, Op2Info,
200                                   Opd1PropInfo, Opd2PropInfo);
201   }
202 
203   // Legalize the type.
204   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
205 
206   int ISD = TLI->InstructionOpcodeToISD(Opcode);
207   assert(ISD && "Invalid opcode");
208 
209   if (ISD == ISD::MUL && Args.size() == 2 && LT.second.isVector() &&
210       LT.second.getScalarType() == MVT::i32) {
211     // Check if the operands can be represented as a smaller datatype.
212     bool Op1Signed = false, Op2Signed = false;
213     unsigned Op1MinSize = BaseT::minRequiredElementSize(Args[0], Op1Signed);
214     unsigned Op2MinSize = BaseT::minRequiredElementSize(Args[1], Op2Signed);
215     unsigned OpMinSize = std::max(Op1MinSize, Op2MinSize);
216 
217     // If both are representable as i15 and at least one is zero-extended,
218     // then we can treat this as PMADDWD which has the same costs
219     // as a vXi16 multiply..
220     if (OpMinSize <= 15 && (!Op1Signed || !Op2Signed) && !ST->isPMADDWDSlow())
221       LT.second =
222           MVT::getVectorVT(MVT::i16, 2 * LT.second.getVectorNumElements());
223   }
224 
225   if ((ISD == ISD::SDIV || ISD == ISD::SREM || ISD == ISD::UDIV ||
226        ISD == ISD::UREM) &&
227       (Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
228        Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) &&
229       Opd2PropInfo == TargetTransformInfo::OP_PowerOf2) {
230     if (ISD == ISD::SDIV || ISD == ISD::SREM) {
231       // On X86, vector signed division by constants power-of-two are
232       // normally expanded to the sequence SRA + SRL + ADD + SRA.
233       // The OperandValue properties may not be the same as that of the previous
234       // operation; conservatively assume OP_None.
235       InstructionCost Cost =
236           2 * getArithmeticInstrCost(Instruction::AShr, Ty, CostKind, Op1Info,
237                                      Op2Info, TargetTransformInfo::OP_None,
238                                      TargetTransformInfo::OP_None);
239       Cost += getArithmeticInstrCost(Instruction::LShr, Ty, CostKind, Op1Info,
240                                      Op2Info, TargetTransformInfo::OP_None,
241                                      TargetTransformInfo::OP_None);
242       Cost += getArithmeticInstrCost(Instruction::Add, Ty, CostKind, Op1Info,
243                                      Op2Info, TargetTransformInfo::OP_None,
244                                      TargetTransformInfo::OP_None);
245 
246       if (ISD == ISD::SREM) {
247         // For SREM: (X % C) is the equivalent of (X - (X/C)*C)
248         Cost += getArithmeticInstrCost(Instruction::Mul, Ty, CostKind, Op1Info,
249                                        Op2Info);
250         Cost += getArithmeticInstrCost(Instruction::Sub, Ty, CostKind, Op1Info,
251                                        Op2Info);
252       }
253 
254       return Cost;
255     }
256 
257     // Vector unsigned division/remainder will be simplified to shifts/masks.
258     if (ISD == ISD::UDIV)
259       return getArithmeticInstrCost(Instruction::LShr, Ty, CostKind, Op1Info,
260                                     Op2Info, TargetTransformInfo::OP_None,
261                                     TargetTransformInfo::OP_None);
262 
263     else // UREM
264       return getArithmeticInstrCost(Instruction::And, Ty, CostKind, Op1Info,
265                                     Op2Info, TargetTransformInfo::OP_None,
266                                     TargetTransformInfo::OP_None);
267   }
268 
269   static const CostTblEntry GLMCostTable[] = {
270     { ISD::FDIV,  MVT::f32,   18 }, // divss
271     { ISD::FDIV,  MVT::v4f32, 35 }, // divps
272     { ISD::FDIV,  MVT::f64,   33 }, // divsd
273     { ISD::FDIV,  MVT::v2f64, 65 }, // divpd
274   };
275 
276   if (ST->useGLMDivSqrtCosts())
277     if (const auto *Entry = CostTableLookup(GLMCostTable, ISD,
278                                             LT.second))
279       return LT.first * Entry->Cost;
280 
281   static const CostTblEntry SLMCostTable[] = {
282     { ISD::MUL,   MVT::v4i32, 11 }, // pmulld
283     { ISD::MUL,   MVT::v8i16, 2  }, // pmullw
284     { ISD::FMUL,  MVT::f64,   2  }, // mulsd
285     { ISD::FMUL,  MVT::v2f64, 4  }, // mulpd
286     { ISD::FMUL,  MVT::v4f32, 2  }, // mulps
287     { ISD::FDIV,  MVT::f32,   17 }, // divss
288     { ISD::FDIV,  MVT::v4f32, 39 }, // divps
289     { ISD::FDIV,  MVT::f64,   32 }, // divsd
290     { ISD::FDIV,  MVT::v2f64, 69 }, // divpd
291     { ISD::FADD,  MVT::v2f64, 2  }, // addpd
292     { ISD::FSUB,  MVT::v2f64, 2  }, // subpd
293     // v2i64/v4i64 mul is custom lowered as a series of long:
294     // multiplies(3), shifts(3) and adds(2)
295     // slm muldq version throughput is 2 and addq throughput 4
296     // thus: 3X2 (muldq throughput) + 3X1 (shift throughput) +
297     //       3X4 (addq throughput) = 17
298     { ISD::MUL,   MVT::v2i64, 17 },
299     // slm addq\subq throughput is 4
300     { ISD::ADD,   MVT::v2i64, 4  },
301     { ISD::SUB,   MVT::v2i64, 4  },
302   };
303 
304   if (ST->isSLM()) {
305     if (Args.size() == 2 && ISD == ISD::MUL && LT.second == MVT::v4i32) {
306       // Check if the operands can be shrinked into a smaller datatype.
307       // TODO: Merge this into generiic vXi32 MUL patterns above.
308       bool Op1Signed = false;
309       unsigned Op1MinSize = BaseT::minRequiredElementSize(Args[0], Op1Signed);
310       bool Op2Signed = false;
311       unsigned Op2MinSize = BaseT::minRequiredElementSize(Args[1], Op2Signed);
312 
313       bool SignedMode = Op1Signed || Op2Signed;
314       unsigned OpMinSize = std::max(Op1MinSize, Op2MinSize);
315 
316       if (OpMinSize <= 7)
317         return LT.first * 3; // pmullw/sext
318       if (!SignedMode && OpMinSize <= 8)
319         return LT.first * 3; // pmullw/zext
320       if (OpMinSize <= 15)
321         return LT.first * 5; // pmullw/pmulhw/pshuf
322       if (!SignedMode && OpMinSize <= 16)
323         return LT.first * 5; // pmullw/pmulhw/pshuf
324     }
325 
326     if (const auto *Entry = CostTableLookup(SLMCostTable, ISD,
327                                             LT.second)) {
328       return LT.first * Entry->Cost;
329     }
330   }
331 
332   static const CostTblEntry AVX512BWUniformConstCostTable[] = {
333     { ISD::SHL,  MVT::v64i8,   2 }, // psllw + pand.
334     { ISD::SRL,  MVT::v64i8,   2 }, // psrlw + pand.
335     { ISD::SRA,  MVT::v64i8,   4 }, // psrlw, pand, pxor, psubb.
336   };
337 
338   if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
339       ST->hasBWI()) {
340     if (const auto *Entry = CostTableLookup(AVX512BWUniformConstCostTable, ISD,
341                                             LT.second))
342       return LT.first * Entry->Cost;
343   }
344 
345   static const CostTblEntry AVX512UniformConstCostTable[] = {
346     { ISD::SRA,  MVT::v2i64,   1 },
347     { ISD::SRA,  MVT::v4i64,   1 },
348     { ISD::SRA,  MVT::v8i64,   1 },
349 
350     { ISD::SHL,  MVT::v64i8,   4 }, // psllw + pand.
351     { ISD::SRL,  MVT::v64i8,   4 }, // psrlw + pand.
352     { ISD::SRA,  MVT::v64i8,   8 }, // psrlw, pand, pxor, psubb.
353 
354     { ISD::SDIV, MVT::v16i32,  6 }, // pmuludq sequence
355     { ISD::SREM, MVT::v16i32,  8 }, // pmuludq+mul+sub sequence
356     { ISD::UDIV, MVT::v16i32,  5 }, // pmuludq sequence
357     { ISD::UREM, MVT::v16i32,  7 }, // pmuludq+mul+sub sequence
358   };
359 
360   if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
361       ST->hasAVX512()) {
362     if (const auto *Entry = CostTableLookup(AVX512UniformConstCostTable, ISD,
363                                             LT.second))
364       return LT.first * Entry->Cost;
365   }
366 
367   static const CostTblEntry AVX2UniformConstCostTable[] = {
368     { ISD::SHL,  MVT::v32i8,   2 }, // psllw + pand.
369     { ISD::SRL,  MVT::v32i8,   2 }, // psrlw + pand.
370     { ISD::SRA,  MVT::v32i8,   4 }, // psrlw, pand, pxor, psubb.
371 
372     { ISD::SRA,  MVT::v4i64,   4 }, // 2 x psrad + shuffle.
373 
374     { ISD::SDIV, MVT::v8i32,   6 }, // pmuludq sequence
375     { ISD::SREM, MVT::v8i32,   8 }, // pmuludq+mul+sub sequence
376     { ISD::UDIV, MVT::v8i32,   5 }, // pmuludq sequence
377     { ISD::UREM, MVT::v8i32,   7 }, // pmuludq+mul+sub sequence
378   };
379 
380   if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
381       ST->hasAVX2()) {
382     if (const auto *Entry = CostTableLookup(AVX2UniformConstCostTable, ISD,
383                                             LT.second))
384       return LT.first * Entry->Cost;
385   }
386 
387   static const CostTblEntry SSE2UniformConstCostTable[] = {
388     { ISD::SHL,  MVT::v16i8,     2 }, // psllw + pand.
389     { ISD::SRL,  MVT::v16i8,     2 }, // psrlw + pand.
390     { ISD::SRA,  MVT::v16i8,     4 }, // psrlw, pand, pxor, psubb.
391 
392     { ISD::SHL,  MVT::v32i8,   4+2 }, // 2*(psllw + pand) + split.
393     { ISD::SRL,  MVT::v32i8,   4+2 }, // 2*(psrlw + pand) + split.
394     { ISD::SRA,  MVT::v32i8,   8+2 }, // 2*(psrlw, pand, pxor, psubb) + split.
395 
396     { ISD::SDIV, MVT::v8i32,  12+2 }, // 2*pmuludq sequence + split.
397     { ISD::SREM, MVT::v8i32,  16+2 }, // 2*pmuludq+mul+sub sequence + split.
398     { ISD::SDIV, MVT::v4i32,     6 }, // pmuludq sequence
399     { ISD::SREM, MVT::v4i32,     8 }, // pmuludq+mul+sub sequence
400     { ISD::UDIV, MVT::v8i32,  10+2 }, // 2*pmuludq sequence + split.
401     { ISD::UREM, MVT::v8i32,  14+2 }, // 2*pmuludq+mul+sub sequence + split.
402     { ISD::UDIV, MVT::v4i32,     5 }, // pmuludq sequence
403     { ISD::UREM, MVT::v4i32,     7 }, // pmuludq+mul+sub sequence
404   };
405 
406   // XOP has faster vXi8 shifts.
407   if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
408       ST->hasSSE2() && !ST->hasXOP()) {
409     if (const auto *Entry =
410             CostTableLookup(SSE2UniformConstCostTable, ISD, LT.second))
411       return LT.first * Entry->Cost;
412   }
413 
414   static const CostTblEntry AVX512BWConstCostTable[] = {
415     { ISD::SDIV, MVT::v64i8,  14 }, // 2*ext+2*pmulhw sequence
416     { ISD::SREM, MVT::v64i8,  16 }, // 2*ext+2*pmulhw+mul+sub sequence
417     { ISD::UDIV, MVT::v64i8,  14 }, // 2*ext+2*pmulhw sequence
418     { ISD::UREM, MVT::v64i8,  16 }, // 2*ext+2*pmulhw+mul+sub sequence
419     { ISD::SDIV, MVT::v32i16,  6 }, // vpmulhw sequence
420     { ISD::SREM, MVT::v32i16,  8 }, // vpmulhw+mul+sub sequence
421     { ISD::UDIV, MVT::v32i16,  6 }, // vpmulhuw sequence
422     { ISD::UREM, MVT::v32i16,  8 }, // vpmulhuw+mul+sub sequence
423   };
424 
425   if ((Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
426        Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) &&
427       ST->hasBWI()) {
428     if (const auto *Entry =
429             CostTableLookup(AVX512BWConstCostTable, ISD, LT.second))
430       return LT.first * Entry->Cost;
431   }
432 
433   static const CostTblEntry AVX512ConstCostTable[] = {
434     { ISD::SDIV, MVT::v16i32, 15 }, // vpmuldq sequence
435     { ISD::SREM, MVT::v16i32, 17 }, // vpmuldq+mul+sub sequence
436     { ISD::UDIV, MVT::v16i32, 15 }, // vpmuludq sequence
437     { ISD::UREM, MVT::v16i32, 17 }, // vpmuludq+mul+sub sequence
438     { ISD::SDIV, MVT::v64i8,  28 }, // 4*ext+4*pmulhw sequence
439     { ISD::SREM, MVT::v64i8,  32 }, // 4*ext+4*pmulhw+mul+sub sequence
440     { ISD::UDIV, MVT::v64i8,  28 }, // 4*ext+4*pmulhw sequence
441     { ISD::UREM, MVT::v64i8,  32 }, // 4*ext+4*pmulhw+mul+sub sequence
442     { ISD::SDIV, MVT::v32i16, 12 }, // 2*vpmulhw sequence
443     { ISD::SREM, MVT::v32i16, 16 }, // 2*vpmulhw+mul+sub sequence
444     { ISD::UDIV, MVT::v32i16, 12 }, // 2*vpmulhuw sequence
445     { ISD::UREM, MVT::v32i16, 16 }, // 2*vpmulhuw+mul+sub sequence
446   };
447 
448   if ((Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
449        Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) &&
450       ST->hasAVX512()) {
451     if (const auto *Entry =
452             CostTableLookup(AVX512ConstCostTable, ISD, LT.second))
453       return LT.first * Entry->Cost;
454   }
455 
456   static const CostTblEntry AVX2ConstCostTable[] = {
457     { ISD::SDIV, MVT::v32i8,  14 }, // 2*ext+2*pmulhw sequence
458     { ISD::SREM, MVT::v32i8,  16 }, // 2*ext+2*pmulhw+mul+sub sequence
459     { ISD::UDIV, MVT::v32i8,  14 }, // 2*ext+2*pmulhw sequence
460     { ISD::UREM, MVT::v32i8,  16 }, // 2*ext+2*pmulhw+mul+sub sequence
461     { ISD::SDIV, MVT::v16i16,  6 }, // vpmulhw sequence
462     { ISD::SREM, MVT::v16i16,  8 }, // vpmulhw+mul+sub sequence
463     { ISD::UDIV, MVT::v16i16,  6 }, // vpmulhuw sequence
464     { ISD::UREM, MVT::v16i16,  8 }, // vpmulhuw+mul+sub sequence
465     { ISD::SDIV, MVT::v8i32,  15 }, // vpmuldq sequence
466     { ISD::SREM, MVT::v8i32,  19 }, // vpmuldq+mul+sub sequence
467     { ISD::UDIV, MVT::v8i32,  15 }, // vpmuludq sequence
468     { ISD::UREM, MVT::v8i32,  19 }, // vpmuludq+mul+sub sequence
469   };
470 
471   if ((Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
472        Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) &&
473       ST->hasAVX2()) {
474     if (const auto *Entry = CostTableLookup(AVX2ConstCostTable, ISD, LT.second))
475       return LT.first * Entry->Cost;
476   }
477 
478   static const CostTblEntry SSE2ConstCostTable[] = {
479     { ISD::SDIV, MVT::v32i8,  28+2 }, // 4*ext+4*pmulhw sequence + split.
480     { ISD::SREM, MVT::v32i8,  32+2 }, // 4*ext+4*pmulhw+mul+sub sequence + split.
481     { ISD::SDIV, MVT::v16i8,    14 }, // 2*ext+2*pmulhw sequence
482     { ISD::SREM, MVT::v16i8,    16 }, // 2*ext+2*pmulhw+mul+sub sequence
483     { ISD::UDIV, MVT::v32i8,  28+2 }, // 4*ext+4*pmulhw sequence + split.
484     { ISD::UREM, MVT::v32i8,  32+2 }, // 4*ext+4*pmulhw+mul+sub sequence + split.
485     { ISD::UDIV, MVT::v16i8,    14 }, // 2*ext+2*pmulhw sequence
486     { ISD::UREM, MVT::v16i8,    16 }, // 2*ext+2*pmulhw+mul+sub sequence
487     { ISD::SDIV, MVT::v16i16, 12+2 }, // 2*pmulhw sequence + split.
488     { ISD::SREM, MVT::v16i16, 16+2 }, // 2*pmulhw+mul+sub sequence + split.
489     { ISD::SDIV, MVT::v8i16,     6 }, // pmulhw sequence
490     { ISD::SREM, MVT::v8i16,     8 }, // pmulhw+mul+sub sequence
491     { ISD::UDIV, MVT::v16i16, 12+2 }, // 2*pmulhuw sequence + split.
492     { ISD::UREM, MVT::v16i16, 16+2 }, // 2*pmulhuw+mul+sub sequence + split.
493     { ISD::UDIV, MVT::v8i16,     6 }, // pmulhuw sequence
494     { ISD::UREM, MVT::v8i16,     8 }, // pmulhuw+mul+sub sequence
495     { ISD::SDIV, MVT::v8i32,  38+2 }, // 2*pmuludq sequence + split.
496     { ISD::SREM, MVT::v8i32,  48+2 }, // 2*pmuludq+mul+sub sequence + split.
497     { ISD::SDIV, MVT::v4i32,    19 }, // pmuludq sequence
498     { ISD::SREM, MVT::v4i32,    24 }, // pmuludq+mul+sub sequence
499     { ISD::UDIV, MVT::v8i32,  30+2 }, // 2*pmuludq sequence + split.
500     { ISD::UREM, MVT::v8i32,  40+2 }, // 2*pmuludq+mul+sub sequence + split.
501     { ISD::UDIV, MVT::v4i32,    15 }, // pmuludq sequence
502     { ISD::UREM, MVT::v4i32,    20 }, // pmuludq+mul+sub sequence
503   };
504 
505   if ((Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
506        Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) &&
507       ST->hasSSE2()) {
508     // pmuldq sequence.
509     if (ISD == ISD::SDIV && LT.second == MVT::v8i32 && ST->hasAVX())
510       return LT.first * 32;
511     if (ISD == ISD::SREM && LT.second == MVT::v8i32 && ST->hasAVX())
512       return LT.first * 38;
513     if (ISD == ISD::SDIV && LT.second == MVT::v4i32 && ST->hasSSE41())
514       return LT.first * 15;
515     if (ISD == ISD::SREM && LT.second == MVT::v4i32 && ST->hasSSE41())
516       return LT.first * 20;
517 
518     if (const auto *Entry = CostTableLookup(SSE2ConstCostTable, ISD, LT.second))
519       return LT.first * Entry->Cost;
520   }
521 
522   static const CostTblEntry AVX512BWShiftCostTable[] = {
523     { ISD::SHL,   MVT::v16i8,      4 }, // extend/vpsllvw/pack sequence.
524     { ISD::SRL,   MVT::v16i8,      4 }, // extend/vpsrlvw/pack sequence.
525     { ISD::SRA,   MVT::v16i8,      4 }, // extend/vpsravw/pack sequence.
526     { ISD::SHL,   MVT::v32i8,      4 }, // extend/vpsllvw/pack sequence.
527     { ISD::SRL,   MVT::v32i8,      4 }, // extend/vpsrlvw/pack sequence.
528     { ISD::SRA,   MVT::v32i8,      6 }, // extend/vpsravw/pack sequence.
529     { ISD::SHL,   MVT::v64i8,      6 }, // extend/vpsllvw/pack sequence.
530     { ISD::SRL,   MVT::v64i8,      7 }, // extend/vpsrlvw/pack sequence.
531     { ISD::SRA,   MVT::v64i8,     15 }, // extend/vpsravw/pack sequence.
532 
533     { ISD::SHL,   MVT::v8i16,      1 }, // vpsllvw
534     { ISD::SRL,   MVT::v8i16,      1 }, // vpsrlvw
535     { ISD::SRA,   MVT::v8i16,      1 }, // vpsravw
536     { ISD::SHL,   MVT::v16i16,     1 }, // vpsllvw
537     { ISD::SRL,   MVT::v16i16,     1 }, // vpsrlvw
538     { ISD::SRA,   MVT::v16i16,     1 }, // vpsravw
539     { ISD::SHL,   MVT::v32i16,     1 }, // vpsllvw
540     { ISD::SRL,   MVT::v32i16,     1 }, // vpsrlvw
541     { ISD::SRA,   MVT::v32i16,     1 }, // vpsravw
542   };
543 
544   if (ST->hasBWI())
545     if (const auto *Entry = CostTableLookup(AVX512BWShiftCostTable, ISD, LT.second))
546       return LT.first * Entry->Cost;
547 
548   static const CostTblEntry AVX2UniformCostTable[] = {
549     // Uniform splats are cheaper for the following instructions.
550     { ISD::SHL,  MVT::v16i16, 1 }, // psllw.
551     { ISD::SRL,  MVT::v16i16, 1 }, // psrlw.
552     { ISD::SRA,  MVT::v16i16, 1 }, // psraw.
553     { ISD::SHL,  MVT::v32i16, 2 }, // 2*psllw.
554     { ISD::SRL,  MVT::v32i16, 2 }, // 2*psrlw.
555     { ISD::SRA,  MVT::v32i16, 2 }, // 2*psraw.
556 
557     { ISD::SHL,  MVT::v8i32,  1 }, // pslld
558     { ISD::SRL,  MVT::v8i32,  1 }, // psrld
559     { ISD::SRA,  MVT::v8i32,  1 }, // psrad
560     { ISD::SHL,  MVT::v4i64,  1 }, // psllq
561     { ISD::SRL,  MVT::v4i64,  1 }, // psrlq
562   };
563 
564   if (ST->hasAVX2() &&
565       ((Op2Info == TargetTransformInfo::OK_UniformConstantValue) ||
566        (Op2Info == TargetTransformInfo::OK_UniformValue))) {
567     if (const auto *Entry =
568             CostTableLookup(AVX2UniformCostTable, ISD, LT.second))
569       return LT.first * Entry->Cost;
570   }
571 
572   static const CostTblEntry SSE2UniformCostTable[] = {
573     // Uniform splats are cheaper for the following instructions.
574     { ISD::SHL,  MVT::v8i16,  1 }, // psllw.
575     { ISD::SHL,  MVT::v4i32,  1 }, // pslld
576     { ISD::SHL,  MVT::v2i64,  1 }, // psllq.
577 
578     { ISD::SRL,  MVT::v8i16,  1 }, // psrlw.
579     { ISD::SRL,  MVT::v4i32,  1 }, // psrld.
580     { ISD::SRL,  MVT::v2i64,  1 }, // psrlq.
581 
582     { ISD::SRA,  MVT::v8i16,  1 }, // psraw.
583     { ISD::SRA,  MVT::v4i32,  1 }, // psrad.
584   };
585 
586   if (ST->hasSSE2() &&
587       ((Op2Info == TargetTransformInfo::OK_UniformConstantValue) ||
588        (Op2Info == TargetTransformInfo::OK_UniformValue))) {
589     if (const auto *Entry =
590             CostTableLookup(SSE2UniformCostTable, ISD, LT.second))
591       return LT.first * Entry->Cost;
592   }
593 
594   static const CostTblEntry AVX512DQCostTable[] = {
595     { ISD::MUL,  MVT::v2i64, 2 }, // pmullq
596     { ISD::MUL,  MVT::v4i64, 2 }, // pmullq
597     { ISD::MUL,  MVT::v8i64, 2 }  // pmullq
598   };
599 
600   // Look for AVX512DQ lowering tricks for custom cases.
601   if (ST->hasDQI())
602     if (const auto *Entry = CostTableLookup(AVX512DQCostTable, ISD, LT.second))
603       return LT.first * Entry->Cost;
604 
605   static const CostTblEntry AVX512BWCostTable[] = {
606     { ISD::SHL,   MVT::v64i8,     11 }, // vpblendvb sequence.
607     { ISD::SRL,   MVT::v64i8,     11 }, // vpblendvb sequence.
608     { ISD::SRA,   MVT::v64i8,     24 }, // vpblendvb sequence.
609   };
610 
611   // Look for AVX512BW lowering tricks for custom cases.
612   if (ST->hasBWI())
613     if (const auto *Entry = CostTableLookup(AVX512BWCostTable, ISD, LT.second))
614       return LT.first * Entry->Cost;
615 
616   static const CostTblEntry AVX512CostTable[] = {
617     { ISD::SHL,     MVT::v4i32,      1 },
618     { ISD::SRL,     MVT::v4i32,      1 },
619     { ISD::SRA,     MVT::v4i32,      1 },
620     { ISD::SHL,     MVT::v8i32,      1 },
621     { ISD::SRL,     MVT::v8i32,      1 },
622     { ISD::SRA,     MVT::v8i32,      1 },
623     { ISD::SHL,     MVT::v16i32,     1 },
624     { ISD::SRL,     MVT::v16i32,     1 },
625     { ISD::SRA,     MVT::v16i32,     1 },
626 
627     { ISD::SHL,     MVT::v2i64,      1 },
628     { ISD::SRL,     MVT::v2i64,      1 },
629     { ISD::SHL,     MVT::v4i64,      1 },
630     { ISD::SRL,     MVT::v4i64,      1 },
631     { ISD::SHL,     MVT::v8i64,      1 },
632     { ISD::SRL,     MVT::v8i64,      1 },
633 
634     { ISD::SRA,     MVT::v2i64,      1 },
635     { ISD::SRA,     MVT::v4i64,      1 },
636     { ISD::SRA,     MVT::v8i64,      1 },
637 
638     { ISD::MUL,     MVT::v16i32,     1 }, // pmulld (Skylake from agner.org)
639     { ISD::MUL,     MVT::v8i32,      1 }, // pmulld (Skylake from agner.org)
640     { ISD::MUL,     MVT::v4i32,      1 }, // pmulld (Skylake from agner.org)
641     { ISD::MUL,     MVT::v8i64,      6 }, // 3*pmuludq/3*shift/2*add
642 
643     { ISD::FNEG,    MVT::v8f64,      1 }, // Skylake from http://www.agner.org/
644     { ISD::FADD,    MVT::v8f64,      1 }, // Skylake from http://www.agner.org/
645     { ISD::FSUB,    MVT::v8f64,      1 }, // Skylake from http://www.agner.org/
646     { ISD::FMUL,    MVT::v8f64,      1 }, // Skylake from http://www.agner.org/
647     { ISD::FDIV,    MVT::f64,        4 }, // Skylake from http://www.agner.org/
648     { ISD::FDIV,    MVT::v2f64,      4 }, // Skylake from http://www.agner.org/
649     { ISD::FDIV,    MVT::v4f64,      8 }, // Skylake from http://www.agner.org/
650     { ISD::FDIV,    MVT::v8f64,     16 }, // Skylake from http://www.agner.org/
651 
652     { ISD::FNEG,    MVT::v16f32,     1 }, // Skylake from http://www.agner.org/
653     { ISD::FADD,    MVT::v16f32,     1 }, // Skylake from http://www.agner.org/
654     { ISD::FSUB,    MVT::v16f32,     1 }, // Skylake from http://www.agner.org/
655     { ISD::FMUL,    MVT::v16f32,     1 }, // Skylake from http://www.agner.org/
656     { ISD::FDIV,    MVT::f32,        3 }, // Skylake from http://www.agner.org/
657     { ISD::FDIV,    MVT::v4f32,      3 }, // Skylake from http://www.agner.org/
658     { ISD::FDIV,    MVT::v8f32,      5 }, // Skylake from http://www.agner.org/
659     { ISD::FDIV,    MVT::v16f32,    10 }, // Skylake from http://www.agner.org/
660   };
661 
662   if (ST->hasAVX512())
663     if (const auto *Entry = CostTableLookup(AVX512CostTable, ISD, LT.second))
664       return LT.first * Entry->Cost;
665 
666   static const CostTblEntry AVX2ShiftCostTable[] = {
667     // Shifts on vXi64/vXi32 on AVX2 is legal even though we declare to
668     // customize them to detect the cases where shift amount is a scalar one.
669     { ISD::SHL,     MVT::v4i32,    2 }, // vpsllvd (Haswell from agner.org)
670     { ISD::SRL,     MVT::v4i32,    2 }, // vpsrlvd (Haswell from agner.org)
671     { ISD::SRA,     MVT::v4i32,    2 }, // vpsravd (Haswell from agner.org)
672     { ISD::SHL,     MVT::v8i32,    2 }, // vpsllvd (Haswell from agner.org)
673     { ISD::SRL,     MVT::v8i32,    2 }, // vpsrlvd (Haswell from agner.org)
674     { ISD::SRA,     MVT::v8i32,    2 }, // vpsravd (Haswell from agner.org)
675     { ISD::SHL,     MVT::v2i64,    1 }, // vpsllvq (Haswell from agner.org)
676     { ISD::SRL,     MVT::v2i64,    1 }, // vpsrlvq (Haswell from agner.org)
677     { ISD::SHL,     MVT::v4i64,    1 }, // vpsllvq (Haswell from agner.org)
678     { ISD::SRL,     MVT::v4i64,    1 }, // vpsrlvq (Haswell from agner.org)
679   };
680 
681   if (ST->hasAVX512()) {
682     if (ISD == ISD::SHL && LT.second == MVT::v32i16 &&
683         (Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
684          Op2Info == TargetTransformInfo::OK_NonUniformConstantValue))
685       // On AVX512, a packed v32i16 shift left by a constant build_vector
686       // is lowered into a vector multiply (vpmullw).
687       return getArithmeticInstrCost(Instruction::Mul, Ty, CostKind,
688                                     Op1Info, Op2Info,
689                                     TargetTransformInfo::OP_None,
690                                     TargetTransformInfo::OP_None);
691   }
692 
693   // Look for AVX2 lowering tricks (XOP is always better at v4i32 shifts).
694   if (ST->hasAVX2() && !(ST->hasXOP() && LT.second == MVT::v4i32)) {
695     if (ISD == ISD::SHL && LT.second == MVT::v16i16 &&
696         (Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
697          Op2Info == TargetTransformInfo::OK_NonUniformConstantValue))
698       // On AVX2, a packed v16i16 shift left by a constant build_vector
699       // is lowered into a vector multiply (vpmullw).
700       return getArithmeticInstrCost(Instruction::Mul, Ty, CostKind,
701                                     Op1Info, Op2Info,
702                                     TargetTransformInfo::OP_None,
703                                     TargetTransformInfo::OP_None);
704 
705     if (const auto *Entry = CostTableLookup(AVX2ShiftCostTable, ISD, LT.second))
706       return LT.first * Entry->Cost;
707   }
708 
709   static const CostTblEntry XOPShiftCostTable[] = {
710     // 128bit shifts take 1cy, but right shifts require negation beforehand.
711     { ISD::SHL,     MVT::v16i8,    1 },
712     { ISD::SRL,     MVT::v16i8,    2 },
713     { ISD::SRA,     MVT::v16i8,    2 },
714     { ISD::SHL,     MVT::v8i16,    1 },
715     { ISD::SRL,     MVT::v8i16,    2 },
716     { ISD::SRA,     MVT::v8i16,    2 },
717     { ISD::SHL,     MVT::v4i32,    1 },
718     { ISD::SRL,     MVT::v4i32,    2 },
719     { ISD::SRA,     MVT::v4i32,    2 },
720     { ISD::SHL,     MVT::v2i64,    1 },
721     { ISD::SRL,     MVT::v2i64,    2 },
722     { ISD::SRA,     MVT::v2i64,    2 },
723     // 256bit shifts require splitting if AVX2 didn't catch them above.
724     { ISD::SHL,     MVT::v32i8,  2+2 },
725     { ISD::SRL,     MVT::v32i8,  4+2 },
726     { ISD::SRA,     MVT::v32i8,  4+2 },
727     { ISD::SHL,     MVT::v16i16, 2+2 },
728     { ISD::SRL,     MVT::v16i16, 4+2 },
729     { ISD::SRA,     MVT::v16i16, 4+2 },
730     { ISD::SHL,     MVT::v8i32,  2+2 },
731     { ISD::SRL,     MVT::v8i32,  4+2 },
732     { ISD::SRA,     MVT::v8i32,  4+2 },
733     { ISD::SHL,     MVT::v4i64,  2+2 },
734     { ISD::SRL,     MVT::v4i64,  4+2 },
735     { ISD::SRA,     MVT::v4i64,  4+2 },
736   };
737 
738   // Look for XOP lowering tricks.
739   if (ST->hasXOP()) {
740     // If the right shift is constant then we'll fold the negation so
741     // it's as cheap as a left shift.
742     int ShiftISD = ISD;
743     if ((ShiftISD == ISD::SRL || ShiftISD == ISD::SRA) &&
744         (Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
745          Op2Info == TargetTransformInfo::OK_NonUniformConstantValue))
746       ShiftISD = ISD::SHL;
747     if (const auto *Entry =
748             CostTableLookup(XOPShiftCostTable, ShiftISD, LT.second))
749       return LT.first * Entry->Cost;
750   }
751 
752   static const CostTblEntry SSE2UniformShiftCostTable[] = {
753     // Uniform splats are cheaper for the following instructions.
754     { ISD::SHL,  MVT::v16i16, 2+2 }, // 2*psllw + split.
755     { ISD::SHL,  MVT::v8i32,  2+2 }, // 2*pslld + split.
756     { ISD::SHL,  MVT::v4i64,  2+2 }, // 2*psllq + split.
757 
758     { ISD::SRL,  MVT::v16i16, 2+2 }, // 2*psrlw + split.
759     { ISD::SRL,  MVT::v8i32,  2+2 }, // 2*psrld + split.
760     { ISD::SRL,  MVT::v4i64,  2+2 }, // 2*psrlq + split.
761 
762     { ISD::SRA,  MVT::v16i16, 2+2 }, // 2*psraw + split.
763     { ISD::SRA,  MVT::v8i32,  2+2 }, // 2*psrad + split.
764     { ISD::SRA,  MVT::v2i64,    4 }, // 2*psrad + shuffle.
765     { ISD::SRA,  MVT::v4i64,  8+2 }, // 2*(2*psrad + shuffle) + split.
766   };
767 
768   if (ST->hasSSE2() &&
769       ((Op2Info == TargetTransformInfo::OK_UniformConstantValue) ||
770        (Op2Info == TargetTransformInfo::OK_UniformValue))) {
771 
772     // Handle AVX2 uniform v4i64 ISD::SRA, it's not worth a table.
773     if (ISD == ISD::SRA && LT.second == MVT::v4i64 && ST->hasAVX2())
774       return LT.first * 4; // 2*psrad + shuffle.
775 
776     if (const auto *Entry =
777             CostTableLookup(SSE2UniformShiftCostTable, ISD, LT.second))
778       return LT.first * Entry->Cost;
779   }
780 
781   if (ISD == ISD::SHL &&
782       Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) {
783     MVT VT = LT.second;
784     // Vector shift left by non uniform constant can be lowered
785     // into vector multiply.
786     if (((VT == MVT::v8i16 || VT == MVT::v4i32) && ST->hasSSE2()) ||
787         ((VT == MVT::v16i16 || VT == MVT::v8i32) && ST->hasAVX()))
788       ISD = ISD::MUL;
789   }
790 
791   static const CostTblEntry AVX2CostTable[] = {
792     { ISD::SHL,  MVT::v16i8,      6 }, // vpblendvb sequence.
793     { ISD::SHL,  MVT::v32i8,      6 }, // vpblendvb sequence.
794     { ISD::SHL,  MVT::v64i8,     12 }, // 2*vpblendvb sequence.
795     { ISD::SHL,  MVT::v8i16,      5 }, // extend/vpsrlvd/pack sequence.
796     { ISD::SHL,  MVT::v16i16,     7 }, // extend/vpsrlvd/pack sequence.
797     { ISD::SHL,  MVT::v32i16,    14 }, // 2*extend/vpsrlvd/pack sequence.
798 
799     { ISD::SRL,  MVT::v16i8,      6 }, // vpblendvb sequence.
800     { ISD::SRL,  MVT::v32i8,      6 }, // vpblendvb sequence.
801     { ISD::SRL,  MVT::v64i8,     12 }, // 2*vpblendvb sequence.
802     { ISD::SRL,  MVT::v8i16,      5 }, // extend/vpsrlvd/pack sequence.
803     { ISD::SRL,  MVT::v16i16,     7 }, // extend/vpsrlvd/pack sequence.
804     { ISD::SRL,  MVT::v32i16,    14 }, // 2*extend/vpsrlvd/pack sequence.
805 
806     { ISD::SRA,  MVT::v16i8,     17 }, // vpblendvb sequence.
807     { ISD::SRA,  MVT::v32i8,     17 }, // vpblendvb sequence.
808     { ISD::SRA,  MVT::v64i8,     34 }, // 2*vpblendvb sequence.
809     { ISD::SRA,  MVT::v8i16,      5 }, // extend/vpsravd/pack sequence.
810     { ISD::SRA,  MVT::v16i16,     7 }, // extend/vpsravd/pack sequence.
811     { ISD::SRA,  MVT::v32i16,    14 }, // 2*extend/vpsravd/pack sequence.
812     { ISD::SRA,  MVT::v2i64,      2 }, // srl/xor/sub sequence.
813     { ISD::SRA,  MVT::v4i64,      2 }, // srl/xor/sub sequence.
814 
815     { ISD::SUB,  MVT::v32i8,      1 }, // psubb
816     { ISD::ADD,  MVT::v32i8,      1 }, // paddb
817     { ISD::SUB,  MVT::v16i16,     1 }, // psubw
818     { ISD::ADD,  MVT::v16i16,     1 }, // paddw
819     { ISD::SUB,  MVT::v8i32,      1 }, // psubd
820     { ISD::ADD,  MVT::v8i32,      1 }, // paddd
821     { ISD::SUB,  MVT::v4i64,      1 }, // psubq
822     { ISD::ADD,  MVT::v4i64,      1 }, // paddq
823 
824     { ISD::MUL,  MVT::v16i16,     1 }, // pmullw
825     { ISD::MUL,  MVT::v8i32,      2 }, // pmulld (Haswell from agner.org)
826     { ISD::MUL,  MVT::v4i64,      6 }, // 3*pmuludq/3*shift/2*add
827 
828     { ISD::FNEG, MVT::v4f64,      1 }, // Haswell from http://www.agner.org/
829     { ISD::FNEG, MVT::v8f32,      1 }, // Haswell from http://www.agner.org/
830     { ISD::FADD, MVT::v4f64,      1 }, // Haswell from http://www.agner.org/
831     { ISD::FADD, MVT::v8f32,      1 }, // Haswell from http://www.agner.org/
832     { ISD::FSUB, MVT::v4f64,      1 }, // Haswell from http://www.agner.org/
833     { ISD::FSUB, MVT::v8f32,      1 }, // Haswell from http://www.agner.org/
834     { ISD::FMUL, MVT::f64,        1 }, // Haswell from http://www.agner.org/
835     { ISD::FMUL, MVT::v2f64,      1 }, // Haswell from http://www.agner.org/
836     { ISD::FMUL, MVT::v4f64,      1 }, // Haswell from http://www.agner.org/
837     { ISD::FMUL, MVT::v8f32,      1 }, // Haswell from http://www.agner.org/
838 
839     { ISD::FDIV, MVT::f32,        7 }, // Haswell from http://www.agner.org/
840     { ISD::FDIV, MVT::v4f32,      7 }, // Haswell from http://www.agner.org/
841     { ISD::FDIV, MVT::v8f32,     14 }, // Haswell from http://www.agner.org/
842     { ISD::FDIV, MVT::f64,       14 }, // Haswell from http://www.agner.org/
843     { ISD::FDIV, MVT::v2f64,     14 }, // Haswell from http://www.agner.org/
844     { ISD::FDIV, MVT::v4f64,     28 }, // Haswell from http://www.agner.org/
845   };
846 
847   // Look for AVX2 lowering tricks for custom cases.
848   if (ST->hasAVX2())
849     if (const auto *Entry = CostTableLookup(AVX2CostTable, ISD, LT.second))
850       return LT.first * Entry->Cost;
851 
852   static const CostTblEntry AVX1CostTable[] = {
853     // We don't have to scalarize unsupported ops. We can issue two half-sized
854     // operations and we only need to extract the upper YMM half.
855     // Two ops + 1 extract + 1 insert = 4.
856     { ISD::MUL,     MVT::v16i16,     4 },
857     { ISD::MUL,     MVT::v8i32,      5 }, // BTVER2 from http://www.agner.org/
858     { ISD::MUL,     MVT::v4i64,     12 },
859 
860     { ISD::SUB,     MVT::v32i8,      4 },
861     { ISD::ADD,     MVT::v32i8,      4 },
862     { ISD::SUB,     MVT::v16i16,     4 },
863     { ISD::ADD,     MVT::v16i16,     4 },
864     { ISD::SUB,     MVT::v8i32,      4 },
865     { ISD::ADD,     MVT::v8i32,      4 },
866     { ISD::SUB,     MVT::v4i64,      4 },
867     { ISD::ADD,     MVT::v4i64,      4 },
868 
869     { ISD::SHL,     MVT::v32i8,     22 }, // pblendvb sequence + split.
870     { ISD::SHL,     MVT::v8i16,      6 }, // pblendvb sequence.
871     { ISD::SHL,     MVT::v16i16,    13 }, // pblendvb sequence + split.
872     { ISD::SHL,     MVT::v4i32,      3 }, // pslld/paddd/cvttps2dq/pmulld
873     { ISD::SHL,     MVT::v8i32,      9 }, // pslld/paddd/cvttps2dq/pmulld + split
874     { ISD::SHL,     MVT::v2i64,      2 }, // Shift each lane + blend.
875     { ISD::SHL,     MVT::v4i64,      6 }, // Shift each lane + blend + split.
876 
877     { ISD::SRL,     MVT::v32i8,     23 }, // pblendvb sequence + split.
878     { ISD::SRL,     MVT::v16i16,    28 }, // pblendvb sequence + split.
879     { ISD::SRL,     MVT::v4i32,      6 }, // Shift each lane + blend.
880     { ISD::SRL,     MVT::v8i32,     14 }, // Shift each lane + blend + split.
881     { ISD::SRL,     MVT::v2i64,      2 }, // Shift each lane + blend.
882     { ISD::SRL,     MVT::v4i64,      6 }, // Shift each lane + blend + split.
883 
884     { ISD::SRA,     MVT::v32i8,     44 }, // pblendvb sequence + split.
885     { ISD::SRA,     MVT::v16i16,    28 }, // pblendvb sequence + split.
886     { ISD::SRA,     MVT::v4i32,      6 }, // Shift each lane + blend.
887     { ISD::SRA,     MVT::v8i32,     14 }, // Shift each lane + blend + split.
888     { ISD::SRA,     MVT::v2i64,      5 }, // Shift each lane + blend.
889     { ISD::SRA,     MVT::v4i64,     12 }, // Shift each lane + blend + split.
890 
891     { ISD::FNEG,    MVT::v4f64,      2 }, // BTVER2 from http://www.agner.org/
892     { ISD::FNEG,    MVT::v8f32,      2 }, // BTVER2 from http://www.agner.org/
893 
894     { ISD::FMUL,    MVT::f64,        2 }, // BTVER2 from http://www.agner.org/
895     { ISD::FMUL,    MVT::v2f64,      2 }, // BTVER2 from http://www.agner.org/
896     { ISD::FMUL,    MVT::v4f64,      4 }, // BTVER2 from http://www.agner.org/
897 
898     { ISD::FDIV,    MVT::f32,       14 }, // SNB from http://www.agner.org/
899     { ISD::FDIV,    MVT::v4f32,     14 }, // SNB from http://www.agner.org/
900     { ISD::FDIV,    MVT::v8f32,     28 }, // SNB from http://www.agner.org/
901     { ISD::FDIV,    MVT::f64,       22 }, // SNB from http://www.agner.org/
902     { ISD::FDIV,    MVT::v2f64,     22 }, // SNB from http://www.agner.org/
903     { ISD::FDIV,    MVT::v4f64,     44 }, // SNB from http://www.agner.org/
904   };
905 
906   if (ST->hasAVX())
907     if (const auto *Entry = CostTableLookup(AVX1CostTable, ISD, LT.second))
908       return LT.first * Entry->Cost;
909 
910   static const CostTblEntry SSE42CostTable[] = {
911     { ISD::FADD, MVT::f64,     1 }, // Nehalem from http://www.agner.org/
912     { ISD::FADD, MVT::f32,     1 }, // Nehalem from http://www.agner.org/
913     { ISD::FADD, MVT::v2f64,   1 }, // Nehalem from http://www.agner.org/
914     { ISD::FADD, MVT::v4f32,   1 }, // Nehalem from http://www.agner.org/
915 
916     { ISD::FSUB, MVT::f64,     1 }, // Nehalem from http://www.agner.org/
917     { ISD::FSUB, MVT::f32 ,    1 }, // Nehalem from http://www.agner.org/
918     { ISD::FSUB, MVT::v2f64,   1 }, // Nehalem from http://www.agner.org/
919     { ISD::FSUB, MVT::v4f32,   1 }, // Nehalem from http://www.agner.org/
920 
921     { ISD::FMUL, MVT::f64,     1 }, // Nehalem from http://www.agner.org/
922     { ISD::FMUL, MVT::f32,     1 }, // Nehalem from http://www.agner.org/
923     { ISD::FMUL, MVT::v2f64,   1 }, // Nehalem from http://www.agner.org/
924     { ISD::FMUL, MVT::v4f32,   1 }, // Nehalem from http://www.agner.org/
925 
926     { ISD::FDIV,  MVT::f32,   14 }, // Nehalem from http://www.agner.org/
927     { ISD::FDIV,  MVT::v4f32, 14 }, // Nehalem from http://www.agner.org/
928     { ISD::FDIV,  MVT::f64,   22 }, // Nehalem from http://www.agner.org/
929     { ISD::FDIV,  MVT::v2f64, 22 }, // Nehalem from http://www.agner.org/
930 
931     { ISD::MUL,   MVT::v2i64,  6 }  // 3*pmuludq/3*shift/2*add
932   };
933 
934   if (ST->hasSSE42())
935     if (const auto *Entry = CostTableLookup(SSE42CostTable, ISD, LT.second))
936       return LT.first * Entry->Cost;
937 
938   static const CostTblEntry SSE41CostTable[] = {
939     { ISD::SHL,  MVT::v16i8,      10 }, // pblendvb sequence.
940     { ISD::SHL,  MVT::v8i16,      11 }, // pblendvb sequence.
941     { ISD::SHL,  MVT::v4i32,       4 }, // pslld/paddd/cvttps2dq/pmulld
942 
943     { ISD::SRL,  MVT::v16i8,      11 }, // pblendvb sequence.
944     { ISD::SRL,  MVT::v8i16,      13 }, // pblendvb sequence.
945     { ISD::SRL,  MVT::v4i32,      16 }, // Shift each lane + blend.
946 
947     { ISD::SRA,  MVT::v16i8,      21 }, // pblendvb sequence.
948     { ISD::SRA,  MVT::v8i16,      13 }, // pblendvb sequence.
949 
950     { ISD::MUL,  MVT::v4i32,       2 }  // pmulld (Nehalem from agner.org)
951   };
952 
953   if (ST->hasSSE41())
954     if (const auto *Entry = CostTableLookup(SSE41CostTable, ISD, LT.second))
955       return LT.first * Entry->Cost;
956 
957   static const CostTblEntry SSE2CostTable[] = {
958     // We don't correctly identify costs of casts because they are marked as
959     // custom.
960     { ISD::SHL,  MVT::v16i8,      13 }, // cmpgtb sequence.
961     { ISD::SHL,  MVT::v8i16,      25 }, // cmpgtw sequence.
962     { ISD::SHL,  MVT::v4i32,      16 }, // pslld/paddd/cvttps2dq/pmuludq.
963     { ISD::SHL,  MVT::v2i64,       4 }, // splat+shuffle sequence.
964 
965     { ISD::SRL,  MVT::v16i8,      14 }, // cmpgtb sequence.
966     { ISD::SRL,  MVT::v8i16,      16 }, // cmpgtw sequence.
967     { ISD::SRL,  MVT::v4i32,      12 }, // Shift each lane + blend.
968     { ISD::SRL,  MVT::v2i64,       4 }, // splat+shuffle sequence.
969 
970     { ISD::SRA,  MVT::v16i8,      27 }, // unpacked cmpgtb sequence.
971     { ISD::SRA,  MVT::v8i16,      16 }, // cmpgtw sequence.
972     { ISD::SRA,  MVT::v4i32,      12 }, // Shift each lane + blend.
973     { ISD::SRA,  MVT::v2i64,       8 }, // srl/xor/sub splat+shuffle sequence.
974 
975     { ISD::MUL,  MVT::v8i16,       1 }, // pmullw
976     { ISD::MUL,  MVT::v4i32,       6 }, // 3*pmuludq/4*shuffle
977     { ISD::MUL,  MVT::v2i64,       8 }, // 3*pmuludq/3*shift/2*add
978 
979     { ISD::FDIV, MVT::f32,        23 }, // Pentium IV from http://www.agner.org/
980     { ISD::FDIV, MVT::v4f32,      39 }, // Pentium IV from http://www.agner.org/
981     { ISD::FDIV, MVT::f64,        38 }, // Pentium IV from http://www.agner.org/
982     { ISD::FDIV, MVT::v2f64,      69 }, // Pentium IV from http://www.agner.org/
983 
984     { ISD::FNEG, MVT::f32,         1 }, // Pentium IV from http://www.agner.org/
985     { ISD::FNEG, MVT::f64,         1 }, // Pentium IV from http://www.agner.org/
986     { ISD::FNEG, MVT::v4f32,       1 }, // Pentium IV from http://www.agner.org/
987     { ISD::FNEG, MVT::v2f64,       1 }, // Pentium IV from http://www.agner.org/
988 
989     { ISD::FADD, MVT::f32,         2 }, // Pentium IV from http://www.agner.org/
990     { ISD::FADD, MVT::f64,         2 }, // Pentium IV from http://www.agner.org/
991 
992     { ISD::FSUB, MVT::f32,         2 }, // Pentium IV from http://www.agner.org/
993     { ISD::FSUB, MVT::f64,         2 }, // Pentium IV from http://www.agner.org/
994   };
995 
996   if (ST->hasSSE2())
997     if (const auto *Entry = CostTableLookup(SSE2CostTable, ISD, LT.second))
998       return LT.first * Entry->Cost;
999 
1000   static const CostTblEntry SSE1CostTable[] = {
1001     { ISD::FDIV, MVT::f32,   17 }, // Pentium III from http://www.agner.org/
1002     { ISD::FDIV, MVT::v4f32, 34 }, // Pentium III from http://www.agner.org/
1003 
1004     { ISD::FNEG, MVT::f32,    2 }, // Pentium III from http://www.agner.org/
1005     { ISD::FNEG, MVT::v4f32,  2 }, // Pentium III from http://www.agner.org/
1006 
1007     { ISD::FADD, MVT::f32,    1 }, // Pentium III from http://www.agner.org/
1008     { ISD::FADD, MVT::v4f32,  2 }, // Pentium III from http://www.agner.org/
1009 
1010     { ISD::FSUB, MVT::f32,    1 }, // Pentium III from http://www.agner.org/
1011     { ISD::FSUB, MVT::v4f32,  2 }, // Pentium III from http://www.agner.org/
1012   };
1013 
1014   if (ST->hasSSE1())
1015     if (const auto *Entry = CostTableLookup(SSE1CostTable, ISD, LT.second))
1016       return LT.first * Entry->Cost;
1017 
1018   static const CostTblEntry X64CostTbl[] = { // 64-bit targets
1019     { ISD::ADD,  MVT::i64,    1 }, // Core (Merom) from http://www.agner.org/
1020     { ISD::SUB,  MVT::i64,    1 }, // Core (Merom) from http://www.agner.org/
1021   };
1022 
1023   if (ST->is64Bit())
1024     if (const auto *Entry = CostTableLookup(X64CostTbl, ISD, LT.second))
1025       return LT.first * Entry->Cost;
1026 
1027   static const CostTblEntry X86CostTbl[] = { // 32 or 64-bit targets
1028     { ISD::ADD,  MVT::i8,    1 }, // Pentium III from http://www.agner.org/
1029     { ISD::ADD,  MVT::i16,   1 }, // Pentium III from http://www.agner.org/
1030     { ISD::ADD,  MVT::i32,   1 }, // Pentium III from http://www.agner.org/
1031 
1032     { ISD::SUB,  MVT::i8,    1 }, // Pentium III from http://www.agner.org/
1033     { ISD::SUB,  MVT::i16,   1 }, // Pentium III from http://www.agner.org/
1034     { ISD::SUB,  MVT::i32,   1 }, // Pentium III from http://www.agner.org/
1035   };
1036 
1037   if (const auto *Entry = CostTableLookup(X86CostTbl, ISD, LT.second))
1038     return LT.first * Entry->Cost;
1039 
1040   // It is not a good idea to vectorize division. We have to scalarize it and
1041   // in the process we will often end up having to spilling regular
1042   // registers. The overhead of division is going to dominate most kernels
1043   // anyways so try hard to prevent vectorization of division - it is
1044   // generally a bad idea. Assume somewhat arbitrarily that we have to be able
1045   // to hide "20 cycles" for each lane.
1046   if (LT.second.isVector() && (ISD == ISD::SDIV || ISD == ISD::SREM ||
1047                                ISD == ISD::UDIV || ISD == ISD::UREM)) {
1048     InstructionCost ScalarCost = getArithmeticInstrCost(
1049         Opcode, Ty->getScalarType(), CostKind, Op1Info, Op2Info,
1050         TargetTransformInfo::OP_None, TargetTransformInfo::OP_None);
1051     return 20 * LT.first * LT.second.getVectorNumElements() * ScalarCost;
1052   }
1053 
1054   // Fallback to the default implementation.
1055   return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, Op2Info);
1056 }
1057 
1058 InstructionCost X86TTIImpl::getShuffleCost(TTI::ShuffleKind Kind,
1059                                            VectorType *BaseTp,
1060                                            ArrayRef<int> Mask, int Index,
1061                                            VectorType *SubTp) {
1062   // 64-bit packed float vectors (v2f32) are widened to type v4f32.
1063   // 64-bit packed integer vectors (v2i32) are widened to type v4i32.
1064   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, BaseTp);
1065 
1066   Kind = improveShuffleKindFromMask(Kind, Mask);
1067   // Treat Transpose as 2-op shuffles - there's no difference in lowering.
1068   if (Kind == TTI::SK_Transpose)
1069     Kind = TTI::SK_PermuteTwoSrc;
1070 
1071   // For Broadcasts we are splatting the first element from the first input
1072   // register, so only need to reference that input and all the output
1073   // registers are the same.
1074   if (Kind == TTI::SK_Broadcast)
1075     LT.first = 1;
1076 
1077   // Subvector extractions are free if they start at the beginning of a
1078   // vector and cheap if the subvectors are aligned.
1079   if (Kind == TTI::SK_ExtractSubvector && LT.second.isVector()) {
1080     int NumElts = LT.second.getVectorNumElements();
1081     if ((Index % NumElts) == 0)
1082       return 0;
1083     std::pair<InstructionCost, MVT> SubLT =
1084         TLI->getTypeLegalizationCost(DL, SubTp);
1085     if (SubLT.second.isVector()) {
1086       int NumSubElts = SubLT.second.getVectorNumElements();
1087       if ((Index % NumSubElts) == 0 && (NumElts % NumSubElts) == 0)
1088         return SubLT.first;
1089       // Handle some cases for widening legalization. For now we only handle
1090       // cases where the original subvector was naturally aligned and evenly
1091       // fit in its legalized subvector type.
1092       // FIXME: Remove some of the alignment restrictions.
1093       // FIXME: We can use permq for 64-bit or larger extracts from 256-bit
1094       // vectors.
1095       int OrigSubElts = cast<FixedVectorType>(SubTp)->getNumElements();
1096       if (NumSubElts > OrigSubElts && (Index % OrigSubElts) == 0 &&
1097           (NumSubElts % OrigSubElts) == 0 &&
1098           LT.second.getVectorElementType() ==
1099               SubLT.second.getVectorElementType() &&
1100           LT.second.getVectorElementType().getSizeInBits() ==
1101               BaseTp->getElementType()->getPrimitiveSizeInBits()) {
1102         assert(NumElts >= NumSubElts && NumElts > OrigSubElts &&
1103                "Unexpected number of elements!");
1104         auto *VecTy = FixedVectorType::get(BaseTp->getElementType(),
1105                                            LT.second.getVectorNumElements());
1106         auto *SubTy = FixedVectorType::get(BaseTp->getElementType(),
1107                                            SubLT.second.getVectorNumElements());
1108         int ExtractIndex = alignDown((Index % NumElts), NumSubElts);
1109         InstructionCost ExtractCost = getShuffleCost(
1110             TTI::SK_ExtractSubvector, VecTy, None, ExtractIndex, SubTy);
1111 
1112         // If the original size is 32-bits or more, we can use pshufd. Otherwise
1113         // if we have SSSE3 we can use pshufb.
1114         if (SubTp->getPrimitiveSizeInBits() >= 32 || ST->hasSSSE3())
1115           return ExtractCost + 1; // pshufd or pshufb
1116 
1117         assert(SubTp->getPrimitiveSizeInBits() == 16 &&
1118                "Unexpected vector size");
1119 
1120         return ExtractCost + 2; // worst case pshufhw + pshufd
1121       }
1122     }
1123   }
1124 
1125   // Subvector insertions are cheap if the subvectors are aligned.
1126   // Note that in general, the insertion starting at the beginning of a vector
1127   // isn't free, because we need to preserve the rest of the wide vector.
1128   if (Kind == TTI::SK_InsertSubvector && LT.second.isVector()) {
1129     int NumElts = LT.second.getVectorNumElements();
1130     std::pair<InstructionCost, MVT> SubLT =
1131         TLI->getTypeLegalizationCost(DL, SubTp);
1132     if (SubLT.second.isVector()) {
1133       int NumSubElts = SubLT.second.getVectorNumElements();
1134       if ((Index % NumSubElts) == 0 && (NumElts % NumSubElts) == 0)
1135         return SubLT.first;
1136     }
1137 
1138     // If the insertion isn't aligned, treat it like a 2-op shuffle.
1139     Kind = TTI::SK_PermuteTwoSrc;
1140   }
1141 
1142   // Handle some common (illegal) sub-vector types as they are often very cheap
1143   // to shuffle even on targets without PSHUFB.
1144   EVT VT = TLI->getValueType(DL, BaseTp);
1145   if (VT.isSimple() && VT.isVector() && VT.getSizeInBits() < 128 &&
1146       !ST->hasSSSE3()) {
1147      static const CostTblEntry SSE2SubVectorShuffleTbl[] = {
1148       {TTI::SK_Broadcast,        MVT::v4i16, 1}, // pshuflw
1149       {TTI::SK_Broadcast,        MVT::v2i16, 1}, // pshuflw
1150       {TTI::SK_Broadcast,        MVT::v8i8,  2}, // punpck/pshuflw
1151       {TTI::SK_Broadcast,        MVT::v4i8,  2}, // punpck/pshuflw
1152       {TTI::SK_Broadcast,        MVT::v2i8,  1}, // punpck
1153 
1154       {TTI::SK_Reverse,          MVT::v4i16, 1}, // pshuflw
1155       {TTI::SK_Reverse,          MVT::v2i16, 1}, // pshuflw
1156       {TTI::SK_Reverse,          MVT::v4i8,  3}, // punpck/pshuflw/packus
1157       {TTI::SK_Reverse,          MVT::v2i8,  1}, // punpck
1158 
1159       {TTI::SK_PermuteTwoSrc,    MVT::v4i16, 2}, // punpck/pshuflw
1160       {TTI::SK_PermuteTwoSrc,    MVT::v2i16, 2}, // punpck/pshuflw
1161       {TTI::SK_PermuteTwoSrc,    MVT::v8i8,  7}, // punpck/pshuflw
1162       {TTI::SK_PermuteTwoSrc,    MVT::v4i8,  4}, // punpck/pshuflw
1163       {TTI::SK_PermuteTwoSrc,    MVT::v2i8,  2}, // punpck
1164 
1165       {TTI::SK_PermuteSingleSrc, MVT::v4i16, 1}, // pshuflw
1166       {TTI::SK_PermuteSingleSrc, MVT::v2i16, 1}, // pshuflw
1167       {TTI::SK_PermuteSingleSrc, MVT::v8i8,  5}, // punpck/pshuflw
1168       {TTI::SK_PermuteSingleSrc, MVT::v4i8,  3}, // punpck/pshuflw
1169       {TTI::SK_PermuteSingleSrc, MVT::v2i8,  1}, // punpck
1170     };
1171 
1172     if (ST->hasSSE2())
1173       if (const auto *Entry =
1174               CostTableLookup(SSE2SubVectorShuffleTbl, Kind, VT.getSimpleVT()))
1175         return Entry->Cost;
1176   }
1177 
1178   // We are going to permute multiple sources and the result will be in multiple
1179   // destinations. Providing an accurate cost only for splits where the element
1180   // type remains the same.
1181   if (Kind == TTI::SK_PermuteSingleSrc && LT.first != 1) {
1182     MVT LegalVT = LT.second;
1183     if (LegalVT.isVector() &&
1184         LegalVT.getVectorElementType().getSizeInBits() ==
1185             BaseTp->getElementType()->getPrimitiveSizeInBits() &&
1186         LegalVT.getVectorNumElements() <
1187             cast<FixedVectorType>(BaseTp)->getNumElements()) {
1188 
1189       unsigned VecTySize = DL.getTypeStoreSize(BaseTp);
1190       unsigned LegalVTSize = LegalVT.getStoreSize();
1191       // Number of source vectors after legalization:
1192       unsigned NumOfSrcs = (VecTySize + LegalVTSize - 1) / LegalVTSize;
1193       // Number of destination vectors after legalization:
1194       InstructionCost NumOfDests = LT.first;
1195 
1196       auto *SingleOpTy = FixedVectorType::get(BaseTp->getElementType(),
1197                                               LegalVT.getVectorNumElements());
1198 
1199       InstructionCost NumOfShuffles = (NumOfSrcs - 1) * NumOfDests;
1200       return NumOfShuffles * getShuffleCost(TTI::SK_PermuteTwoSrc, SingleOpTy,
1201                                             None, 0, nullptr);
1202     }
1203 
1204     return BaseT::getShuffleCost(Kind, BaseTp, Mask, Index, SubTp);
1205   }
1206 
1207   // For 2-input shuffles, we must account for splitting the 2 inputs into many.
1208   if (Kind == TTI::SK_PermuteTwoSrc && LT.first != 1) {
1209     // We assume that source and destination have the same vector type.
1210     InstructionCost NumOfDests = LT.first;
1211     InstructionCost NumOfShufflesPerDest = LT.first * 2 - 1;
1212     LT.first = NumOfDests * NumOfShufflesPerDest;
1213   }
1214 
1215   static const CostTblEntry AVX512FP16ShuffleTbl[] = {
1216       {TTI::SK_Broadcast, MVT::v32f16, 1}, // vpbroadcastw
1217       {TTI::SK_Broadcast, MVT::v16f16, 1}, // vpbroadcastw
1218       {TTI::SK_Broadcast, MVT::v8f16, 1},  // vpbroadcastw
1219 
1220       {TTI::SK_Reverse, MVT::v32f16, 2}, // vpermw
1221       {TTI::SK_Reverse, MVT::v16f16, 2}, // vpermw
1222       {TTI::SK_Reverse, MVT::v8f16, 1},  // vpshufb
1223 
1224       {TTI::SK_PermuteSingleSrc, MVT::v32f16, 2}, // vpermw
1225       {TTI::SK_PermuteSingleSrc, MVT::v16f16, 2}, // vpermw
1226       {TTI::SK_PermuteSingleSrc, MVT::v8f16, 1},  // vpshufb
1227 
1228       {TTI::SK_PermuteTwoSrc, MVT::v32f16, 2}, // vpermt2w
1229       {TTI::SK_PermuteTwoSrc, MVT::v16f16, 2}, // vpermt2w
1230       {TTI::SK_PermuteTwoSrc, MVT::v8f16, 2}   // vpermt2w
1231   };
1232 
1233   if (!ST->useSoftFloat() && ST->hasFP16())
1234     if (const auto *Entry =
1235             CostTableLookup(AVX512FP16ShuffleTbl, Kind, LT.second))
1236       return LT.first * Entry->Cost;
1237 
1238   static const CostTblEntry AVX512VBMIShuffleTbl[] = {
1239       {TTI::SK_Reverse, MVT::v64i8, 1}, // vpermb
1240       {TTI::SK_Reverse, MVT::v32i8, 1}, // vpermb
1241 
1242       {TTI::SK_PermuteSingleSrc, MVT::v64i8, 1}, // vpermb
1243       {TTI::SK_PermuteSingleSrc, MVT::v32i8, 1}, // vpermb
1244 
1245       {TTI::SK_PermuteTwoSrc, MVT::v64i8, 2}, // vpermt2b
1246       {TTI::SK_PermuteTwoSrc, MVT::v32i8, 2}, // vpermt2b
1247       {TTI::SK_PermuteTwoSrc, MVT::v16i8, 2}  // vpermt2b
1248   };
1249 
1250   if (ST->hasVBMI())
1251     if (const auto *Entry =
1252             CostTableLookup(AVX512VBMIShuffleTbl, Kind, LT.second))
1253       return LT.first * Entry->Cost;
1254 
1255   static const CostTblEntry AVX512BWShuffleTbl[] = {
1256       {TTI::SK_Broadcast, MVT::v32i16, 1}, // vpbroadcastw
1257       {TTI::SK_Broadcast, MVT::v64i8, 1},  // vpbroadcastb
1258 
1259       {TTI::SK_Reverse, MVT::v32i16, 2}, // vpermw
1260       {TTI::SK_Reverse, MVT::v16i16, 2}, // vpermw
1261       {TTI::SK_Reverse, MVT::v64i8, 2},  // pshufb + vshufi64x2
1262 
1263       {TTI::SK_PermuteSingleSrc, MVT::v32i16, 2}, // vpermw
1264       {TTI::SK_PermuteSingleSrc, MVT::v16i16, 2}, // vpermw
1265       {TTI::SK_PermuteSingleSrc, MVT::v64i8, 8},  // extend to v32i16
1266 
1267       {TTI::SK_PermuteTwoSrc, MVT::v32i16, 2}, // vpermt2w
1268       {TTI::SK_PermuteTwoSrc, MVT::v16i16, 2}, // vpermt2w
1269       {TTI::SK_PermuteTwoSrc, MVT::v8i16, 2},  // vpermt2w
1270       {TTI::SK_PermuteTwoSrc, MVT::v64i8, 19}, // 6 * v32i8 + 1
1271 
1272       {TTI::SK_Select, MVT::v32i16, 1}, // vblendmw
1273       {TTI::SK_Select, MVT::v64i8,  1}, // vblendmb
1274   };
1275 
1276   if (ST->hasBWI())
1277     if (const auto *Entry =
1278             CostTableLookup(AVX512BWShuffleTbl, Kind, LT.second))
1279       return LT.first * Entry->Cost;
1280 
1281   static const CostTblEntry AVX512ShuffleTbl[] = {
1282       {TTI::SK_Broadcast, MVT::v8f64, 1},  // vbroadcastpd
1283       {TTI::SK_Broadcast, MVT::v16f32, 1}, // vbroadcastps
1284       {TTI::SK_Broadcast, MVT::v8i64, 1},  // vpbroadcastq
1285       {TTI::SK_Broadcast, MVT::v16i32, 1}, // vpbroadcastd
1286       {TTI::SK_Broadcast, MVT::v32i16, 1}, // vpbroadcastw
1287       {TTI::SK_Broadcast, MVT::v64i8, 1},  // vpbroadcastb
1288 
1289       {TTI::SK_Reverse, MVT::v8f64, 1},  // vpermpd
1290       {TTI::SK_Reverse, MVT::v16f32, 1}, // vpermps
1291       {TTI::SK_Reverse, MVT::v8i64, 1},  // vpermq
1292       {TTI::SK_Reverse, MVT::v16i32, 1}, // vpermd
1293       {TTI::SK_Reverse, MVT::v32i16, 7}, // per mca
1294       {TTI::SK_Reverse, MVT::v64i8,  7}, // per mca
1295 
1296       {TTI::SK_PermuteSingleSrc, MVT::v8f64, 1},  // vpermpd
1297       {TTI::SK_PermuteSingleSrc, MVT::v4f64, 1},  // vpermpd
1298       {TTI::SK_PermuteSingleSrc, MVT::v2f64, 1},  // vpermpd
1299       {TTI::SK_PermuteSingleSrc, MVT::v16f32, 1}, // vpermps
1300       {TTI::SK_PermuteSingleSrc, MVT::v8f32, 1},  // vpermps
1301       {TTI::SK_PermuteSingleSrc, MVT::v4f32, 1},  // vpermps
1302       {TTI::SK_PermuteSingleSrc, MVT::v8i64, 1},  // vpermq
1303       {TTI::SK_PermuteSingleSrc, MVT::v4i64, 1},  // vpermq
1304       {TTI::SK_PermuteSingleSrc, MVT::v2i64, 1},  // vpermq
1305       {TTI::SK_PermuteSingleSrc, MVT::v16i32, 1}, // vpermd
1306       {TTI::SK_PermuteSingleSrc, MVT::v8i32, 1},  // vpermd
1307       {TTI::SK_PermuteSingleSrc, MVT::v4i32, 1},  // vpermd
1308       {TTI::SK_PermuteSingleSrc, MVT::v16i8, 1},  // pshufb
1309 
1310       {TTI::SK_PermuteTwoSrc, MVT::v8f64, 1},  // vpermt2pd
1311       {TTI::SK_PermuteTwoSrc, MVT::v16f32, 1}, // vpermt2ps
1312       {TTI::SK_PermuteTwoSrc, MVT::v8i64, 1},  // vpermt2q
1313       {TTI::SK_PermuteTwoSrc, MVT::v16i32, 1}, // vpermt2d
1314       {TTI::SK_PermuteTwoSrc, MVT::v4f64, 1},  // vpermt2pd
1315       {TTI::SK_PermuteTwoSrc, MVT::v8f32, 1},  // vpermt2ps
1316       {TTI::SK_PermuteTwoSrc, MVT::v4i64, 1},  // vpermt2q
1317       {TTI::SK_PermuteTwoSrc, MVT::v8i32, 1},  // vpermt2d
1318       {TTI::SK_PermuteTwoSrc, MVT::v2f64, 1},  // vpermt2pd
1319       {TTI::SK_PermuteTwoSrc, MVT::v4f32, 1},  // vpermt2ps
1320       {TTI::SK_PermuteTwoSrc, MVT::v2i64, 1},  // vpermt2q
1321       {TTI::SK_PermuteTwoSrc, MVT::v4i32, 1},  // vpermt2d
1322 
1323       // FIXME: This just applies the type legalization cost rules above
1324       // assuming these completely split.
1325       {TTI::SK_PermuteSingleSrc, MVT::v32i16, 14},
1326       {TTI::SK_PermuteSingleSrc, MVT::v64i8,  14},
1327       {TTI::SK_PermuteTwoSrc,    MVT::v32i16, 42},
1328       {TTI::SK_PermuteTwoSrc,    MVT::v64i8,  42},
1329 
1330       {TTI::SK_Select, MVT::v32i16, 1}, // vpternlogq
1331       {TTI::SK_Select, MVT::v64i8,  1}, // vpternlogq
1332       {TTI::SK_Select, MVT::v8f64,  1}, // vblendmpd
1333       {TTI::SK_Select, MVT::v16f32, 1}, // vblendmps
1334       {TTI::SK_Select, MVT::v8i64,  1}, // vblendmq
1335       {TTI::SK_Select, MVT::v16i32, 1}, // vblendmd
1336   };
1337 
1338   if (ST->hasAVX512())
1339     if (const auto *Entry = CostTableLookup(AVX512ShuffleTbl, Kind, LT.second))
1340       return LT.first * Entry->Cost;
1341 
1342   static const CostTblEntry AVX2ShuffleTbl[] = {
1343       {TTI::SK_Broadcast, MVT::v4f64, 1},  // vbroadcastpd
1344       {TTI::SK_Broadcast, MVT::v8f32, 1},  // vbroadcastps
1345       {TTI::SK_Broadcast, MVT::v4i64, 1},  // vpbroadcastq
1346       {TTI::SK_Broadcast, MVT::v8i32, 1},  // vpbroadcastd
1347       {TTI::SK_Broadcast, MVT::v16i16, 1}, // vpbroadcastw
1348       {TTI::SK_Broadcast, MVT::v32i8, 1},  // vpbroadcastb
1349 
1350       {TTI::SK_Reverse, MVT::v4f64, 1},  // vpermpd
1351       {TTI::SK_Reverse, MVT::v8f32, 1},  // vpermps
1352       {TTI::SK_Reverse, MVT::v4i64, 1},  // vpermq
1353       {TTI::SK_Reverse, MVT::v8i32, 1},  // vpermd
1354       {TTI::SK_Reverse, MVT::v16i16, 2}, // vperm2i128 + pshufb
1355       {TTI::SK_Reverse, MVT::v32i8, 2},  // vperm2i128 + pshufb
1356 
1357       {TTI::SK_Select, MVT::v16i16, 1}, // vpblendvb
1358       {TTI::SK_Select, MVT::v32i8, 1},  // vpblendvb
1359 
1360       {TTI::SK_PermuteSingleSrc, MVT::v4f64, 1},  // vpermpd
1361       {TTI::SK_PermuteSingleSrc, MVT::v8f32, 1},  // vpermps
1362       {TTI::SK_PermuteSingleSrc, MVT::v4i64, 1},  // vpermq
1363       {TTI::SK_PermuteSingleSrc, MVT::v8i32, 1},  // vpermd
1364       {TTI::SK_PermuteSingleSrc, MVT::v16i16, 4}, // vperm2i128 + 2*vpshufb
1365                                                   // + vpblendvb
1366       {TTI::SK_PermuteSingleSrc, MVT::v32i8, 4},  // vperm2i128 + 2*vpshufb
1367                                                   // + vpblendvb
1368 
1369       {TTI::SK_PermuteTwoSrc, MVT::v4f64, 3},  // 2*vpermpd + vblendpd
1370       {TTI::SK_PermuteTwoSrc, MVT::v8f32, 3},  // 2*vpermps + vblendps
1371       {TTI::SK_PermuteTwoSrc, MVT::v4i64, 3},  // 2*vpermq + vpblendd
1372       {TTI::SK_PermuteTwoSrc, MVT::v8i32, 3},  // 2*vpermd + vpblendd
1373       {TTI::SK_PermuteTwoSrc, MVT::v16i16, 7}, // 2*vperm2i128 + 4*vpshufb
1374                                                // + vpblendvb
1375       {TTI::SK_PermuteTwoSrc, MVT::v32i8, 7},  // 2*vperm2i128 + 4*vpshufb
1376                                                // + vpblendvb
1377   };
1378 
1379   if (ST->hasAVX2())
1380     if (const auto *Entry = CostTableLookup(AVX2ShuffleTbl, Kind, LT.second))
1381       return LT.first * Entry->Cost;
1382 
1383   static const CostTblEntry XOPShuffleTbl[] = {
1384       {TTI::SK_PermuteSingleSrc, MVT::v4f64, 2},  // vperm2f128 + vpermil2pd
1385       {TTI::SK_PermuteSingleSrc, MVT::v8f32, 2},  // vperm2f128 + vpermil2ps
1386       {TTI::SK_PermuteSingleSrc, MVT::v4i64, 2},  // vperm2f128 + vpermil2pd
1387       {TTI::SK_PermuteSingleSrc, MVT::v8i32, 2},  // vperm2f128 + vpermil2ps
1388       {TTI::SK_PermuteSingleSrc, MVT::v16i16, 4}, // vextractf128 + 2*vpperm
1389                                                   // + vinsertf128
1390       {TTI::SK_PermuteSingleSrc, MVT::v32i8, 4},  // vextractf128 + 2*vpperm
1391                                                   // + vinsertf128
1392 
1393       {TTI::SK_PermuteTwoSrc, MVT::v16i16, 9}, // 2*vextractf128 + 6*vpperm
1394                                                // + vinsertf128
1395       {TTI::SK_PermuteTwoSrc, MVT::v8i16, 1},  // vpperm
1396       {TTI::SK_PermuteTwoSrc, MVT::v32i8, 9},  // 2*vextractf128 + 6*vpperm
1397                                                // + vinsertf128
1398       {TTI::SK_PermuteTwoSrc, MVT::v16i8, 1},  // vpperm
1399   };
1400 
1401   if (ST->hasXOP())
1402     if (const auto *Entry = CostTableLookup(XOPShuffleTbl, Kind, LT.second))
1403       return LT.first * Entry->Cost;
1404 
1405   static const CostTblEntry AVX1ShuffleTbl[] = {
1406       {TTI::SK_Broadcast, MVT::v4f64, 2},  // vperm2f128 + vpermilpd
1407       {TTI::SK_Broadcast, MVT::v8f32, 2},  // vperm2f128 + vpermilps
1408       {TTI::SK_Broadcast, MVT::v4i64, 2},  // vperm2f128 + vpermilpd
1409       {TTI::SK_Broadcast, MVT::v8i32, 2},  // vperm2f128 + vpermilps
1410       {TTI::SK_Broadcast, MVT::v16i16, 3}, // vpshuflw + vpshufd + vinsertf128
1411       {TTI::SK_Broadcast, MVT::v32i8, 2},  // vpshufb + vinsertf128
1412 
1413       {TTI::SK_Reverse, MVT::v4f64, 2},  // vperm2f128 + vpermilpd
1414       {TTI::SK_Reverse, MVT::v8f32, 2},  // vperm2f128 + vpermilps
1415       {TTI::SK_Reverse, MVT::v4i64, 2},  // vperm2f128 + vpermilpd
1416       {TTI::SK_Reverse, MVT::v8i32, 2},  // vperm2f128 + vpermilps
1417       {TTI::SK_Reverse, MVT::v16i16, 4}, // vextractf128 + 2*pshufb
1418                                          // + vinsertf128
1419       {TTI::SK_Reverse, MVT::v32i8, 4},  // vextractf128 + 2*pshufb
1420                                          // + vinsertf128
1421 
1422       {TTI::SK_Select, MVT::v4i64, 1},  // vblendpd
1423       {TTI::SK_Select, MVT::v4f64, 1},  // vblendpd
1424       {TTI::SK_Select, MVT::v8i32, 1},  // vblendps
1425       {TTI::SK_Select, MVT::v8f32, 1},  // vblendps
1426       {TTI::SK_Select, MVT::v16i16, 3}, // vpand + vpandn + vpor
1427       {TTI::SK_Select, MVT::v32i8, 3},  // vpand + vpandn + vpor
1428 
1429       {TTI::SK_PermuteSingleSrc, MVT::v4f64, 2},  // vperm2f128 + vshufpd
1430       {TTI::SK_PermuteSingleSrc, MVT::v4i64, 2},  // vperm2f128 + vshufpd
1431       {TTI::SK_PermuteSingleSrc, MVT::v8f32, 4},  // 2*vperm2f128 + 2*vshufps
1432       {TTI::SK_PermuteSingleSrc, MVT::v8i32, 4},  // 2*vperm2f128 + 2*vshufps
1433       {TTI::SK_PermuteSingleSrc, MVT::v16i16, 8}, // vextractf128 + 4*pshufb
1434                                                   // + 2*por + vinsertf128
1435       {TTI::SK_PermuteSingleSrc, MVT::v32i8, 8},  // vextractf128 + 4*pshufb
1436                                                   // + 2*por + vinsertf128
1437 
1438       {TTI::SK_PermuteTwoSrc, MVT::v4f64, 3},   // 2*vperm2f128 + vshufpd
1439       {TTI::SK_PermuteTwoSrc, MVT::v4i64, 3},   // 2*vperm2f128 + vshufpd
1440       {TTI::SK_PermuteTwoSrc, MVT::v8f32, 4},   // 2*vperm2f128 + 2*vshufps
1441       {TTI::SK_PermuteTwoSrc, MVT::v8i32, 4},   // 2*vperm2f128 + 2*vshufps
1442       {TTI::SK_PermuteTwoSrc, MVT::v16i16, 15}, // 2*vextractf128 + 8*pshufb
1443                                                 // + 4*por + vinsertf128
1444       {TTI::SK_PermuteTwoSrc, MVT::v32i8, 15},  // 2*vextractf128 + 8*pshufb
1445                                                 // + 4*por + vinsertf128
1446   };
1447 
1448   if (ST->hasAVX())
1449     if (const auto *Entry = CostTableLookup(AVX1ShuffleTbl, Kind, LT.second))
1450       return LT.first * Entry->Cost;
1451 
1452   static const CostTblEntry SSE41ShuffleTbl[] = {
1453       {TTI::SK_Select, MVT::v2i64, 1}, // pblendw
1454       {TTI::SK_Select, MVT::v2f64, 1}, // movsd
1455       {TTI::SK_Select, MVT::v4i32, 1}, // pblendw
1456       {TTI::SK_Select, MVT::v4f32, 1}, // blendps
1457       {TTI::SK_Select, MVT::v8i16, 1}, // pblendw
1458       {TTI::SK_Select, MVT::v16i8, 1}  // pblendvb
1459   };
1460 
1461   if (ST->hasSSE41())
1462     if (const auto *Entry = CostTableLookup(SSE41ShuffleTbl, Kind, LT.second))
1463       return LT.first * Entry->Cost;
1464 
1465   static const CostTblEntry SSSE3ShuffleTbl[] = {
1466       {TTI::SK_Broadcast, MVT::v8i16, 1}, // pshufb
1467       {TTI::SK_Broadcast, MVT::v16i8, 1}, // pshufb
1468 
1469       {TTI::SK_Reverse, MVT::v8i16, 1}, // pshufb
1470       {TTI::SK_Reverse, MVT::v16i8, 1}, // pshufb
1471 
1472       {TTI::SK_Select, MVT::v8i16, 3}, // 2*pshufb + por
1473       {TTI::SK_Select, MVT::v16i8, 3}, // 2*pshufb + por
1474 
1475       {TTI::SK_PermuteSingleSrc, MVT::v8i16, 1}, // pshufb
1476       {TTI::SK_PermuteSingleSrc, MVT::v16i8, 1}, // pshufb
1477 
1478       {TTI::SK_PermuteTwoSrc, MVT::v8i16, 3}, // 2*pshufb + por
1479       {TTI::SK_PermuteTwoSrc, MVT::v16i8, 3}, // 2*pshufb + por
1480   };
1481 
1482   if (ST->hasSSSE3())
1483     if (const auto *Entry = CostTableLookup(SSSE3ShuffleTbl, Kind, LT.second))
1484       return LT.first * Entry->Cost;
1485 
1486   static const CostTblEntry SSE2ShuffleTbl[] = {
1487       {TTI::SK_Broadcast, MVT::v2f64, 1}, // shufpd
1488       {TTI::SK_Broadcast, MVT::v2i64, 1}, // pshufd
1489       {TTI::SK_Broadcast, MVT::v4i32, 1}, // pshufd
1490       {TTI::SK_Broadcast, MVT::v8i16, 2}, // pshuflw + pshufd
1491       {TTI::SK_Broadcast, MVT::v16i8, 3}, // unpck + pshuflw + pshufd
1492 
1493       {TTI::SK_Reverse, MVT::v2f64, 1}, // shufpd
1494       {TTI::SK_Reverse, MVT::v2i64, 1}, // pshufd
1495       {TTI::SK_Reverse, MVT::v4i32, 1}, // pshufd
1496       {TTI::SK_Reverse, MVT::v8i16, 3}, // pshuflw + pshufhw + pshufd
1497       {TTI::SK_Reverse, MVT::v16i8, 9}, // 2*pshuflw + 2*pshufhw
1498                                         // + 2*pshufd + 2*unpck + packus
1499 
1500       {TTI::SK_Select, MVT::v2i64, 1}, // movsd
1501       {TTI::SK_Select, MVT::v2f64, 1}, // movsd
1502       {TTI::SK_Select, MVT::v4i32, 2}, // 2*shufps
1503       {TTI::SK_Select, MVT::v8i16, 3}, // pand + pandn + por
1504       {TTI::SK_Select, MVT::v16i8, 3}, // pand + pandn + por
1505 
1506       {TTI::SK_PermuteSingleSrc, MVT::v2f64, 1}, // shufpd
1507       {TTI::SK_PermuteSingleSrc, MVT::v2i64, 1}, // pshufd
1508       {TTI::SK_PermuteSingleSrc, MVT::v4i32, 1}, // pshufd
1509       {TTI::SK_PermuteSingleSrc, MVT::v8i16, 5}, // 2*pshuflw + 2*pshufhw
1510                                                   // + pshufd/unpck
1511     { TTI::SK_PermuteSingleSrc, MVT::v16i8, 10 }, // 2*pshuflw + 2*pshufhw
1512                                                   // + 2*pshufd + 2*unpck + 2*packus
1513 
1514     { TTI::SK_PermuteTwoSrc,    MVT::v2f64,  1 }, // shufpd
1515     { TTI::SK_PermuteTwoSrc,    MVT::v2i64,  1 }, // shufpd
1516     { TTI::SK_PermuteTwoSrc,    MVT::v4i32,  2 }, // 2*{unpck,movsd,pshufd}
1517     { TTI::SK_PermuteTwoSrc,    MVT::v8i16,  8 }, // blend+permute
1518     { TTI::SK_PermuteTwoSrc,    MVT::v16i8, 13 }, // blend+permute
1519   };
1520 
1521   if (ST->hasSSE2())
1522     if (const auto *Entry = CostTableLookup(SSE2ShuffleTbl, Kind, LT.second))
1523       return LT.first * Entry->Cost;
1524 
1525   static const CostTblEntry SSE1ShuffleTbl[] = {
1526     { TTI::SK_Broadcast,        MVT::v4f32, 1 }, // shufps
1527     { TTI::SK_Reverse,          MVT::v4f32, 1 }, // shufps
1528     { TTI::SK_Select,           MVT::v4f32, 2 }, // 2*shufps
1529     { TTI::SK_PermuteSingleSrc, MVT::v4f32, 1 }, // shufps
1530     { TTI::SK_PermuteTwoSrc,    MVT::v4f32, 2 }, // 2*shufps
1531   };
1532 
1533   if (ST->hasSSE1())
1534     if (const auto *Entry = CostTableLookup(SSE1ShuffleTbl, Kind, LT.second))
1535       return LT.first * Entry->Cost;
1536 
1537   return BaseT::getShuffleCost(Kind, BaseTp, Mask, Index, SubTp);
1538 }
1539 
1540 InstructionCost X86TTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst,
1541                                              Type *Src,
1542                                              TTI::CastContextHint CCH,
1543                                              TTI::TargetCostKind CostKind,
1544                                              const Instruction *I) {
1545   int ISD = TLI->InstructionOpcodeToISD(Opcode);
1546   assert(ISD && "Invalid opcode");
1547 
1548   // TODO: Allow non-throughput costs that aren't binary.
1549   auto AdjustCost = [&CostKind](InstructionCost Cost) -> InstructionCost {
1550     if (CostKind != TTI::TCK_RecipThroughput)
1551       return Cost == 0 ? 0 : 1;
1552     return Cost;
1553   };
1554 
1555   // The cost tables include both specific, custom (non-legal) src/dst type
1556   // conversions and generic, legalized types. We test for customs first, before
1557   // falling back to legalization.
1558   // FIXME: Need a better design of the cost table to handle non-simple types of
1559   // potential massive combinations (elem_num x src_type x dst_type).
1560   static const TypeConversionCostTblEntry AVX512BWConversionTbl[] {
1561     { ISD::SIGN_EXTEND, MVT::v32i16, MVT::v32i8, 1 },
1562     { ISD::ZERO_EXTEND, MVT::v32i16, MVT::v32i8, 1 },
1563 
1564     // Mask sign extend has an instruction.
1565     { ISD::SIGN_EXTEND, MVT::v2i8,   MVT::v2i1,  1 },
1566     { ISD::SIGN_EXTEND, MVT::v2i16,  MVT::v2i1,  1 },
1567     { ISD::SIGN_EXTEND, MVT::v4i8,   MVT::v4i1,  1 },
1568     { ISD::SIGN_EXTEND, MVT::v4i16,  MVT::v4i1,  1 },
1569     { ISD::SIGN_EXTEND, MVT::v8i8,   MVT::v8i1,  1 },
1570     { ISD::SIGN_EXTEND, MVT::v8i16,  MVT::v8i1,  1 },
1571     { ISD::SIGN_EXTEND, MVT::v16i8,  MVT::v16i1, 1 },
1572     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i1, 1 },
1573     { ISD::SIGN_EXTEND, MVT::v32i8,  MVT::v32i1, 1 },
1574     { ISD::SIGN_EXTEND, MVT::v32i16, MVT::v32i1, 1 },
1575     { ISD::SIGN_EXTEND, MVT::v64i8,  MVT::v64i1, 1 },
1576 
1577     // Mask zero extend is a sext + shift.
1578     { ISD::ZERO_EXTEND, MVT::v2i8,   MVT::v2i1,  2 },
1579     { ISD::ZERO_EXTEND, MVT::v2i16,  MVT::v2i1,  2 },
1580     { ISD::ZERO_EXTEND, MVT::v4i8,   MVT::v4i1,  2 },
1581     { ISD::ZERO_EXTEND, MVT::v4i16,  MVT::v4i1,  2 },
1582     { ISD::ZERO_EXTEND, MVT::v8i8,   MVT::v8i1,  2 },
1583     { ISD::ZERO_EXTEND, MVT::v8i16,  MVT::v8i1,  2 },
1584     { ISD::ZERO_EXTEND, MVT::v16i8,  MVT::v16i1, 2 },
1585     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i1, 2 },
1586     { ISD::ZERO_EXTEND, MVT::v32i8,  MVT::v32i1, 2 },
1587     { ISD::ZERO_EXTEND, MVT::v32i16, MVT::v32i1, 2 },
1588     { ISD::ZERO_EXTEND, MVT::v64i8,  MVT::v64i1, 2 },
1589 
1590     { ISD::TRUNCATE,    MVT::v32i8,  MVT::v32i16, 2 },
1591     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v16i16, 2 }, // widen to zmm
1592     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i8,   2 }, // widen to zmm
1593     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i16,  2 }, // widen to zmm
1594     { ISD::TRUNCATE,    MVT::v2i8,   MVT::v2i16,  2 }, // vpmovwb
1595     { ISD::TRUNCATE,    MVT::v4i1,   MVT::v4i8,   2 }, // widen to zmm
1596     { ISD::TRUNCATE,    MVT::v4i1,   MVT::v4i16,  2 }, // widen to zmm
1597     { ISD::TRUNCATE,    MVT::v4i8,   MVT::v4i16,  2 }, // vpmovwb
1598     { ISD::TRUNCATE,    MVT::v8i1,   MVT::v8i8,   2 }, // widen to zmm
1599     { ISD::TRUNCATE,    MVT::v8i1,   MVT::v8i16,  2 }, // widen to zmm
1600     { ISD::TRUNCATE,    MVT::v8i8,   MVT::v8i16,  2 }, // vpmovwb
1601     { ISD::TRUNCATE,    MVT::v16i1,  MVT::v16i8,  2 }, // widen to zmm
1602     { ISD::TRUNCATE,    MVT::v16i1,  MVT::v16i16, 2 }, // widen to zmm
1603     { ISD::TRUNCATE,    MVT::v32i1,  MVT::v32i8,  2 }, // widen to zmm
1604     { ISD::TRUNCATE,    MVT::v32i1,  MVT::v32i16, 2 },
1605     { ISD::TRUNCATE,    MVT::v64i1,  MVT::v64i8,  2 },
1606   };
1607 
1608   static const TypeConversionCostTblEntry AVX512DQConversionTbl[] = {
1609     { ISD::SINT_TO_FP,  MVT::v8f32,  MVT::v8i64,  1 },
1610     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i64,  1 },
1611 
1612     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i64,  1 },
1613     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i64,  1 },
1614 
1615     { ISD::FP_TO_SINT,  MVT::v8i64,  MVT::v8f32,  1 },
1616     { ISD::FP_TO_SINT,  MVT::v8i64,  MVT::v8f64,  1 },
1617 
1618     { ISD::FP_TO_UINT,  MVT::v8i64,  MVT::v8f32,  1 },
1619     { ISD::FP_TO_UINT,  MVT::v8i64,  MVT::v8f64,  1 },
1620   };
1621 
1622   // TODO: For AVX512DQ + AVX512VL, we also have cheap casts for 128-bit and
1623   // 256-bit wide vectors.
1624 
1625   static const TypeConversionCostTblEntry AVX512FConversionTbl[] = {
1626     { ISD::FP_EXTEND, MVT::v8f64,   MVT::v8f32,  1 },
1627     { ISD::FP_EXTEND, MVT::v8f64,   MVT::v16f32, 3 },
1628     { ISD::FP_ROUND,  MVT::v8f32,   MVT::v8f64,  1 },
1629 
1630     { ISD::TRUNCATE,  MVT::v2i1,    MVT::v2i8,   3 }, // sext+vpslld+vptestmd
1631     { ISD::TRUNCATE,  MVT::v4i1,    MVT::v4i8,   3 }, // sext+vpslld+vptestmd
1632     { ISD::TRUNCATE,  MVT::v8i1,    MVT::v8i8,   3 }, // sext+vpslld+vptestmd
1633     { ISD::TRUNCATE,  MVT::v16i1,   MVT::v16i8,  3 }, // sext+vpslld+vptestmd
1634     { ISD::TRUNCATE,  MVT::v2i1,    MVT::v2i16,  3 }, // sext+vpsllq+vptestmq
1635     { ISD::TRUNCATE,  MVT::v4i1,    MVT::v4i16,  3 }, // sext+vpsllq+vptestmq
1636     { ISD::TRUNCATE,  MVT::v8i1,    MVT::v8i16,  3 }, // sext+vpsllq+vptestmq
1637     { ISD::TRUNCATE,  MVT::v16i1,   MVT::v16i16, 3 }, // sext+vpslld+vptestmd
1638     { ISD::TRUNCATE,  MVT::v2i1,    MVT::v2i32,  2 }, // zmm vpslld+vptestmd
1639     { ISD::TRUNCATE,  MVT::v4i1,    MVT::v4i32,  2 }, // zmm vpslld+vptestmd
1640     { ISD::TRUNCATE,  MVT::v8i1,    MVT::v8i32,  2 }, // zmm vpslld+vptestmd
1641     { ISD::TRUNCATE,  MVT::v16i1,   MVT::v16i32, 2 }, // vpslld+vptestmd
1642     { ISD::TRUNCATE,  MVT::v2i1,    MVT::v2i64,  2 }, // zmm vpsllq+vptestmq
1643     { ISD::TRUNCATE,  MVT::v4i1,    MVT::v4i64,  2 }, // zmm vpsllq+vptestmq
1644     { ISD::TRUNCATE,  MVT::v8i1,    MVT::v8i64,  2 }, // vpsllq+vptestmq
1645     { ISD::TRUNCATE,  MVT::v2i8,    MVT::v2i32,  2 }, // vpmovdb
1646     { ISD::TRUNCATE,  MVT::v4i8,    MVT::v4i32,  2 }, // vpmovdb
1647     { ISD::TRUNCATE,  MVT::v16i8,   MVT::v16i32, 2 }, // vpmovdb
1648     { ISD::TRUNCATE,  MVT::v16i16,  MVT::v16i32, 2 }, // vpmovdb
1649     { ISD::TRUNCATE,  MVT::v2i8,    MVT::v2i64,  2 }, // vpmovqb
1650     { ISD::TRUNCATE,  MVT::v2i16,   MVT::v2i64,  1 }, // vpshufb
1651     { ISD::TRUNCATE,  MVT::v8i8,    MVT::v8i64,  2 }, // vpmovqb
1652     { ISD::TRUNCATE,  MVT::v8i16,   MVT::v8i64,  2 }, // vpmovqw
1653     { ISD::TRUNCATE,  MVT::v8i32,   MVT::v8i64,  1 }, // vpmovqd
1654     { ISD::TRUNCATE,  MVT::v4i32,   MVT::v4i64,  1 }, // zmm vpmovqd
1655     { ISD::TRUNCATE,  MVT::v16i8,   MVT::v16i64, 5 },// 2*vpmovqd+concat+vpmovdb
1656 
1657     { ISD::TRUNCATE,  MVT::v16i8,  MVT::v16i16,  3 }, // extend to v16i32
1658     { ISD::TRUNCATE,  MVT::v32i8,  MVT::v32i16,  8 },
1659 
1660     // Sign extend is zmm vpternlogd+vptruncdb.
1661     // Zero extend is zmm broadcast load+vptruncdw.
1662     { ISD::SIGN_EXTEND, MVT::v2i8,   MVT::v2i1,   3 },
1663     { ISD::ZERO_EXTEND, MVT::v2i8,   MVT::v2i1,   4 },
1664     { ISD::SIGN_EXTEND, MVT::v4i8,   MVT::v4i1,   3 },
1665     { ISD::ZERO_EXTEND, MVT::v4i8,   MVT::v4i1,   4 },
1666     { ISD::SIGN_EXTEND, MVT::v8i8,   MVT::v8i1,   3 },
1667     { ISD::ZERO_EXTEND, MVT::v8i8,   MVT::v8i1,   4 },
1668     { ISD::SIGN_EXTEND, MVT::v16i8,  MVT::v16i1,  3 },
1669     { ISD::ZERO_EXTEND, MVT::v16i8,  MVT::v16i1,  4 },
1670 
1671     // Sign extend is zmm vpternlogd+vptruncdw.
1672     // Zero extend is zmm vpternlogd+vptruncdw+vpsrlw.
1673     { ISD::SIGN_EXTEND, MVT::v2i16,  MVT::v2i1,   3 },
1674     { ISD::ZERO_EXTEND, MVT::v2i16,  MVT::v2i1,   4 },
1675     { ISD::SIGN_EXTEND, MVT::v4i16,  MVT::v4i1,   3 },
1676     { ISD::ZERO_EXTEND, MVT::v4i16,  MVT::v4i1,   4 },
1677     { ISD::SIGN_EXTEND, MVT::v8i16,  MVT::v8i1,   3 },
1678     { ISD::ZERO_EXTEND, MVT::v8i16,  MVT::v8i1,   4 },
1679     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i1,  3 },
1680     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i1,  4 },
1681 
1682     { ISD::SIGN_EXTEND, MVT::v2i32,  MVT::v2i1,   1 }, // zmm vpternlogd
1683     { ISD::ZERO_EXTEND, MVT::v2i32,  MVT::v2i1,   2 }, // zmm vpternlogd+psrld
1684     { ISD::SIGN_EXTEND, MVT::v4i32,  MVT::v4i1,   1 }, // zmm vpternlogd
1685     { ISD::ZERO_EXTEND, MVT::v4i32,  MVT::v4i1,   2 }, // zmm vpternlogd+psrld
1686     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i1,   1 }, // zmm vpternlogd
1687     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i1,   2 }, // zmm vpternlogd+psrld
1688     { ISD::SIGN_EXTEND, MVT::v2i64,  MVT::v2i1,   1 }, // zmm vpternlogq
1689     { ISD::ZERO_EXTEND, MVT::v2i64,  MVT::v2i1,   2 }, // zmm vpternlogq+psrlq
1690     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i1,   1 }, // zmm vpternlogq
1691     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i1,   2 }, // zmm vpternlogq+psrlq
1692 
1693     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i1,  1 }, // vpternlogd
1694     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i1,  2 }, // vpternlogd+psrld
1695     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i1,   1 }, // vpternlogq
1696     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i1,   2 }, // vpternlogq+psrlq
1697 
1698     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8,  1 },
1699     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8,  1 },
1700     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i16, 1 },
1701     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i16, 1 },
1702     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i8,   1 },
1703     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i8,   1 },
1704     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i16,  1 },
1705     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i16,  1 },
1706     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i32,  1 },
1707     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i32,  1 },
1708 
1709     { ISD::SIGN_EXTEND, MVT::v32i16, MVT::v32i8,  3 }, // FIXME: May not be right
1710     { ISD::ZERO_EXTEND, MVT::v32i16, MVT::v32i8,  3 }, // FIXME: May not be right
1711 
1712     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i1,   4 },
1713     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i1,  3 },
1714     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v16i8,  2 },
1715     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i8,  1 },
1716     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i16,  2 },
1717     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i16, 1 },
1718     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i32,  1 },
1719     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i32, 1 },
1720 
1721     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i1,   4 },
1722     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i1,  3 },
1723     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v16i8,  2 },
1724     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i8,  1 },
1725     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i16,  2 },
1726     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i16, 1 },
1727     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i32,  1 },
1728     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i32, 1 },
1729     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i64, 26 },
1730     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i64,  5 },
1731 
1732     { ISD::FP_TO_SINT,  MVT::v16i8,  MVT::v16f32, 2 },
1733     { ISD::FP_TO_SINT,  MVT::v16i8,  MVT::v16f64, 7 },
1734     { ISD::FP_TO_SINT,  MVT::v32i8,  MVT::v32f64,15 },
1735     { ISD::FP_TO_SINT,  MVT::v64i8,  MVT::v64f32,11 },
1736     { ISD::FP_TO_SINT,  MVT::v64i8,  MVT::v64f64,31 },
1737     { ISD::FP_TO_SINT,  MVT::v8i16,  MVT::v8f64,  3 },
1738     { ISD::FP_TO_SINT,  MVT::v16i16, MVT::v16f64, 7 },
1739     { ISD::FP_TO_SINT,  MVT::v32i16, MVT::v32f32, 5 },
1740     { ISD::FP_TO_SINT,  MVT::v32i16, MVT::v32f64,15 },
1741     { ISD::FP_TO_SINT,  MVT::v8i32,  MVT::v8f64,  1 },
1742     { ISD::FP_TO_SINT,  MVT::v16i32, MVT::v16f64, 3 },
1743 
1744     { ISD::FP_TO_UINT,  MVT::v8i32,  MVT::v8f64,  1 },
1745     { ISD::FP_TO_UINT,  MVT::v8i16,  MVT::v8f64,  3 },
1746     { ISD::FP_TO_UINT,  MVT::v8i8,   MVT::v8f64,  3 },
1747     { ISD::FP_TO_UINT,  MVT::v16i32, MVT::v16f32, 1 },
1748     { ISD::FP_TO_UINT,  MVT::v16i16, MVT::v16f32, 3 },
1749     { ISD::FP_TO_UINT,  MVT::v16i8,  MVT::v16f32, 3 },
1750   };
1751 
1752   static const TypeConversionCostTblEntry AVX512BWVLConversionTbl[] {
1753     // Mask sign extend has an instruction.
1754     { ISD::SIGN_EXTEND, MVT::v2i8,   MVT::v2i1,  1 },
1755     { ISD::SIGN_EXTEND, MVT::v2i16,  MVT::v2i1,  1 },
1756     { ISD::SIGN_EXTEND, MVT::v4i8,   MVT::v4i1,  1 },
1757     { ISD::SIGN_EXTEND, MVT::v4i16,  MVT::v4i1,  1 },
1758     { ISD::SIGN_EXTEND, MVT::v8i8,   MVT::v8i1,  1 },
1759     { ISD::SIGN_EXTEND, MVT::v8i16,  MVT::v8i1,  1 },
1760     { ISD::SIGN_EXTEND, MVT::v16i8,  MVT::v16i1, 1 },
1761     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i1, 1 },
1762     { ISD::SIGN_EXTEND, MVT::v32i8,  MVT::v32i1, 1 },
1763 
1764     // Mask zero extend is a sext + shift.
1765     { ISD::ZERO_EXTEND, MVT::v2i8,   MVT::v2i1,  2 },
1766     { ISD::ZERO_EXTEND, MVT::v2i16,  MVT::v2i1,  2 },
1767     { ISD::ZERO_EXTEND, MVT::v4i8,   MVT::v4i1,  2 },
1768     { ISD::ZERO_EXTEND, MVT::v4i16,  MVT::v4i1,  2 },
1769     { ISD::ZERO_EXTEND, MVT::v8i8,   MVT::v8i1,  2 },
1770     { ISD::ZERO_EXTEND, MVT::v8i16,  MVT::v8i1,  2 },
1771     { ISD::ZERO_EXTEND, MVT::v16i8,  MVT::v16i1, 2 },
1772     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i1, 2 },
1773     { ISD::ZERO_EXTEND, MVT::v32i8,  MVT::v32i1, 2 },
1774 
1775     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v16i16, 2 },
1776     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i8,   2 }, // vpsllw+vptestmb
1777     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i16,  2 }, // vpsllw+vptestmw
1778     { ISD::TRUNCATE,    MVT::v4i1,   MVT::v4i8,   2 }, // vpsllw+vptestmb
1779     { ISD::TRUNCATE,    MVT::v4i1,   MVT::v4i16,  2 }, // vpsllw+vptestmw
1780     { ISD::TRUNCATE,    MVT::v8i1,   MVT::v8i8,   2 }, // vpsllw+vptestmb
1781     { ISD::TRUNCATE,    MVT::v8i1,   MVT::v8i16,  2 }, // vpsllw+vptestmw
1782     { ISD::TRUNCATE,    MVT::v16i1,  MVT::v16i8,  2 }, // vpsllw+vptestmb
1783     { ISD::TRUNCATE,    MVT::v16i1,  MVT::v16i16, 2 }, // vpsllw+vptestmw
1784     { ISD::TRUNCATE,    MVT::v32i1,  MVT::v32i8,  2 }, // vpsllw+vptestmb
1785   };
1786 
1787   static const TypeConversionCostTblEntry AVX512DQVLConversionTbl[] = {
1788     { ISD::SINT_TO_FP,  MVT::v2f32,  MVT::v2i64,  1 },
1789     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v2i64,  1 },
1790     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v4i64,  1 },
1791     { ISD::SINT_TO_FP,  MVT::v4f64,  MVT::v4i64,  1 },
1792 
1793     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i64,  1 },
1794     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i64,  1 },
1795     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i64,  1 },
1796     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i64,  1 },
1797 
1798     { ISD::FP_TO_SINT,  MVT::v2i64,  MVT::v4f32,  1 },
1799     { ISD::FP_TO_SINT,  MVT::v4i64,  MVT::v4f32,  1 },
1800     { ISD::FP_TO_SINT,  MVT::v2i64,  MVT::v2f64,  1 },
1801     { ISD::FP_TO_SINT,  MVT::v4i64,  MVT::v4f64,  1 },
1802 
1803     { ISD::FP_TO_UINT,  MVT::v2i64,  MVT::v4f32,  1 },
1804     { ISD::FP_TO_UINT,  MVT::v4i64,  MVT::v4f32,  1 },
1805     { ISD::FP_TO_UINT,  MVT::v2i64,  MVT::v2f64,  1 },
1806     { ISD::FP_TO_UINT,  MVT::v4i64,  MVT::v4f64,  1 },
1807   };
1808 
1809   static const TypeConversionCostTblEntry AVX512VLConversionTbl[] = {
1810     { ISD::TRUNCATE,  MVT::v2i1,    MVT::v2i8,   3 }, // sext+vpslld+vptestmd
1811     { ISD::TRUNCATE,  MVT::v4i1,    MVT::v4i8,   3 }, // sext+vpslld+vptestmd
1812     { ISD::TRUNCATE,  MVT::v8i1,    MVT::v8i8,   3 }, // sext+vpslld+vptestmd
1813     { ISD::TRUNCATE,  MVT::v16i1,   MVT::v16i8,  8 }, // split+2*v8i8
1814     { ISD::TRUNCATE,  MVT::v2i1,    MVT::v2i16,  3 }, // sext+vpsllq+vptestmq
1815     { ISD::TRUNCATE,  MVT::v4i1,    MVT::v4i16,  3 }, // sext+vpsllq+vptestmq
1816     { ISD::TRUNCATE,  MVT::v8i1,    MVT::v8i16,  3 }, // sext+vpsllq+vptestmq
1817     { ISD::TRUNCATE,  MVT::v16i1,   MVT::v16i16, 8 }, // split+2*v8i16
1818     { ISD::TRUNCATE,  MVT::v2i1,    MVT::v2i32,  2 }, // vpslld+vptestmd
1819     { ISD::TRUNCATE,  MVT::v4i1,    MVT::v4i32,  2 }, // vpslld+vptestmd
1820     { ISD::TRUNCATE,  MVT::v8i1,    MVT::v8i32,  2 }, // vpslld+vptestmd
1821     { ISD::TRUNCATE,  MVT::v2i1,    MVT::v2i64,  2 }, // vpsllq+vptestmq
1822     { ISD::TRUNCATE,  MVT::v4i1,    MVT::v4i64,  2 }, // vpsllq+vptestmq
1823     { ISD::TRUNCATE,  MVT::v4i32,   MVT::v4i64,  1 }, // vpmovqd
1824     { ISD::TRUNCATE,  MVT::v4i8,    MVT::v4i64,  2 }, // vpmovqb
1825     { ISD::TRUNCATE,  MVT::v4i16,   MVT::v4i64,  2 }, // vpmovqw
1826     { ISD::TRUNCATE,  MVT::v8i8,    MVT::v8i32,  2 }, // vpmovwb
1827 
1828     // sign extend is vpcmpeq+maskedmove+vpmovdw+vpacksswb
1829     // zero extend is vpcmpeq+maskedmove+vpmovdw+vpsrlw+vpackuswb
1830     { ISD::SIGN_EXTEND, MVT::v2i8,   MVT::v2i1,   5 },
1831     { ISD::ZERO_EXTEND, MVT::v2i8,   MVT::v2i1,   6 },
1832     { ISD::SIGN_EXTEND, MVT::v4i8,   MVT::v4i1,   5 },
1833     { ISD::ZERO_EXTEND, MVT::v4i8,   MVT::v4i1,   6 },
1834     { ISD::SIGN_EXTEND, MVT::v8i8,   MVT::v8i1,   5 },
1835     { ISD::ZERO_EXTEND, MVT::v8i8,   MVT::v8i1,   6 },
1836     { ISD::SIGN_EXTEND, MVT::v16i8,  MVT::v16i1, 10 },
1837     { ISD::ZERO_EXTEND, MVT::v16i8,  MVT::v16i1, 12 },
1838 
1839     // sign extend is vpcmpeq+maskedmove+vpmovdw
1840     // zero extend is vpcmpeq+maskedmove+vpmovdw+vpsrlw
1841     { ISD::SIGN_EXTEND, MVT::v2i16,  MVT::v2i1,   4 },
1842     { ISD::ZERO_EXTEND, MVT::v2i16,  MVT::v2i1,   5 },
1843     { ISD::SIGN_EXTEND, MVT::v4i16,  MVT::v4i1,   4 },
1844     { ISD::ZERO_EXTEND, MVT::v4i16,  MVT::v4i1,   5 },
1845     { ISD::SIGN_EXTEND, MVT::v8i16,  MVT::v8i1,   4 },
1846     { ISD::ZERO_EXTEND, MVT::v8i16,  MVT::v8i1,   5 },
1847     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i1, 10 },
1848     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i1, 12 },
1849 
1850     { ISD::SIGN_EXTEND, MVT::v2i32,  MVT::v2i1,   1 }, // vpternlogd
1851     { ISD::ZERO_EXTEND, MVT::v2i32,  MVT::v2i1,   2 }, // vpternlogd+psrld
1852     { ISD::SIGN_EXTEND, MVT::v4i32,  MVT::v4i1,   1 }, // vpternlogd
1853     { ISD::ZERO_EXTEND, MVT::v4i32,  MVT::v4i1,   2 }, // vpternlogd+psrld
1854     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i1,   1 }, // vpternlogd
1855     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i1,   2 }, // vpternlogd+psrld
1856     { ISD::SIGN_EXTEND, MVT::v2i64,  MVT::v2i1,   1 }, // vpternlogq
1857     { ISD::ZERO_EXTEND, MVT::v2i64,  MVT::v2i1,   2 }, // vpternlogq+psrlq
1858     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i1,   1 }, // vpternlogq
1859     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i1,   2 }, // vpternlogq+psrlq
1860 
1861     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v16i8,  1 },
1862     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v16i8,  1 },
1863     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v16i8,  1 },
1864     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v16i8,  1 },
1865     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8,  1 },
1866     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8,  1 },
1867     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v8i16,  1 },
1868     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v8i16,  1 },
1869     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16,  1 },
1870     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16,  1 },
1871     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i32,  1 },
1872     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i32,  1 },
1873 
1874     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v16i8,  1 },
1875     { ISD::SINT_TO_FP,  MVT::v8f32,  MVT::v16i8,  1 },
1876     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v8i16,  1 },
1877     { ISD::SINT_TO_FP,  MVT::v8f32,  MVT::v8i16,  1 },
1878 
1879     { ISD::UINT_TO_FP,  MVT::f32,    MVT::i64,    1 },
1880     { ISD::UINT_TO_FP,  MVT::f64,    MVT::i64,    1 },
1881     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v16i8,  1 },
1882     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v16i8,  1 },
1883     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v8i16,  1 },
1884     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i16,  1 },
1885     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i32,  1 },
1886     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i32,  1 },
1887     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i32,  1 },
1888     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i32,  1 },
1889     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i64,  5 },
1890     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i64,  5 },
1891     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i64,  5 },
1892 
1893     { ISD::FP_TO_SINT,  MVT::v16i8,  MVT::v8f32,  2 },
1894     { ISD::FP_TO_SINT,  MVT::v16i8,  MVT::v16f32, 2 },
1895     { ISD::FP_TO_SINT,  MVT::v32i8,  MVT::v32f32, 5 },
1896 
1897     { ISD::FP_TO_UINT,  MVT::i64,    MVT::f32,    1 },
1898     { ISD::FP_TO_UINT,  MVT::i64,    MVT::f64,    1 },
1899     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v4f32,  1 },
1900     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v2f64,  1 },
1901     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v4f64,  1 },
1902     { ISD::FP_TO_UINT,  MVT::v8i32,  MVT::v8f32,  1 },
1903     { ISD::FP_TO_UINT,  MVT::v8i32,  MVT::v8f64,  1 },
1904   };
1905 
1906   static const TypeConversionCostTblEntry AVX2ConversionTbl[] = {
1907     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i1,   3 },
1908     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i1,   3 },
1909     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i1,   3 },
1910     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i1,   3 },
1911     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i1,  1 },
1912     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i1,  1 },
1913 
1914     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v16i8,  2 },
1915     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v16i8,  2 },
1916     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v16i8,  2 },
1917     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v16i8,  2 },
1918     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8,  2 },
1919     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8,  2 },
1920     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v8i16,  2 },
1921     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v8i16,  2 },
1922     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16,  2 },
1923     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16,  2 },
1924     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i16, 3 },
1925     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i16, 3 },
1926     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i32,  2 },
1927     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i32,  2 },
1928 
1929     { ISD::TRUNCATE,    MVT::v8i1,   MVT::v8i32,  2 },
1930 
1931     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v8i16,  1 },
1932     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v4i32,  1 },
1933     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v2i64,  1 },
1934     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v8i32,  4 },
1935     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v4i64,  4 },
1936     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v4i32,  1 },
1937     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v2i64,  1 },
1938     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v4i64,  5 },
1939     { ISD::TRUNCATE,    MVT::v4i32,  MVT::v4i64,  1 },
1940     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v8i32,  2 },
1941 
1942     { ISD::FP_EXTEND,   MVT::v8f64,  MVT::v8f32,  3 },
1943     { ISD::FP_ROUND,    MVT::v8f32,  MVT::v8f64,  3 },
1944 
1945     { ISD::FP_TO_SINT,  MVT::v16i16, MVT::v8f32,  1 },
1946     { ISD::FP_TO_SINT,  MVT::v4i32,  MVT::v4f64,  1 },
1947     { ISD::FP_TO_SINT,  MVT::v8i32,  MVT::v8f32,  1 },
1948     { ISD::FP_TO_SINT,  MVT::v8i32,  MVT::v8f64,  3 },
1949 
1950     { ISD::FP_TO_UINT,  MVT::i64,    MVT::f32,    3 },
1951     { ISD::FP_TO_UINT,  MVT::i64,    MVT::f64,    3 },
1952     { ISD::FP_TO_UINT,  MVT::v16i16, MVT::v8f32,  1 },
1953     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v4f32,  3 },
1954     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v2f64,  4 },
1955     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v4f64,  4 },
1956     { ISD::FP_TO_UINT,  MVT::v8i32,  MVT::v8f32,  3 },
1957     { ISD::FP_TO_UINT,  MVT::v8i32,  MVT::v4f64,  4 },
1958 
1959     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v16i8,  2 },
1960     { ISD::SINT_TO_FP,  MVT::v8f32,  MVT::v16i8,  2 },
1961     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v8i16,  2 },
1962     { ISD::SINT_TO_FP,  MVT::v8f32,  MVT::v8i16,  2 },
1963     { ISD::SINT_TO_FP,  MVT::v4f64,  MVT::v4i32,  1 },
1964     { ISD::SINT_TO_FP,  MVT::v8f32,  MVT::v8i32,  1 },
1965     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i32,  3 },
1966 
1967     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v16i8,  2 },
1968     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v16i8,  2 },
1969     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v8i16,  2 },
1970     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i16,  2 },
1971     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i32,  2 },
1972     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i32,  1 },
1973     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i32,  2 },
1974     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i32,  2 },
1975     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i32,  2 },
1976     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i32,  4 },
1977   };
1978 
1979   static const TypeConversionCostTblEntry AVXConversionTbl[] = {
1980     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i1,   6 },
1981     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i1,   4 },
1982     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i1,   7 },
1983     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i1,   4 },
1984     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i1,  4 },
1985     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i1,  4 },
1986 
1987     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v16i8,  3 },
1988     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v16i8,  3 },
1989     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v16i8,  3 },
1990     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v16i8,  3 },
1991     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8,  3 },
1992     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8,  3 },
1993     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v8i16,  3 },
1994     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v8i16,  3 },
1995     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16,  3 },
1996     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16,  3 },
1997     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i32,  3 },
1998     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i32,  3 },
1999 
2000     { ISD::TRUNCATE,    MVT::v4i1,   MVT::v4i64,  4 },
2001     { ISD::TRUNCATE,    MVT::v8i1,   MVT::v8i32,  5 },
2002     { ISD::TRUNCATE,    MVT::v16i1,  MVT::v16i16, 4 },
2003     { ISD::TRUNCATE,    MVT::v8i1,   MVT::v8i64,  9 },
2004     { ISD::TRUNCATE,    MVT::v16i1,  MVT::v16i64, 11 },
2005 
2006     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v16i16, 2 }, // and+extract+packuswb
2007     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v8i32,  5 },
2008     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v8i32,  5 },
2009     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v4i64,  5 },
2010     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v4i64,  3 }, // and+extract+2*packusdw
2011     { ISD::TRUNCATE,    MVT::v4i32,  MVT::v4i64,  2 },
2012 
2013     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v4i1,   3 },
2014     { ISD::SINT_TO_FP,  MVT::v4f64,  MVT::v4i1,   3 },
2015     { ISD::SINT_TO_FP,  MVT::v8f32,  MVT::v8i1,   8 },
2016     { ISD::SINT_TO_FP,  MVT::v8f32,  MVT::v16i8,  4 },
2017     { ISD::SINT_TO_FP,  MVT::v4f64,  MVT::v16i8,  2 },
2018     { ISD::SINT_TO_FP,  MVT::v8f32,  MVT::v8i16,  4 },
2019     { ISD::SINT_TO_FP,  MVT::v4f64,  MVT::v8i16,  2 },
2020     { ISD::SINT_TO_FP,  MVT::v4f64,  MVT::v4i32,  2 },
2021     { ISD::SINT_TO_FP,  MVT::v8f32,  MVT::v8i32,  2 },
2022     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i32,  4 },
2023     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v2i64,  5 },
2024     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v4i64,  8 },
2025 
2026     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i1,   7 },
2027     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i1,   7 },
2028     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i1,   6 },
2029     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v16i8,  4 },
2030     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v16i8,  2 },
2031     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i16,  4 },
2032     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v8i16,  2 },
2033     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i32,  4 },
2034     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i32,  4 },
2035     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i32,  5 },
2036     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i32,  6 },
2037     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i32,  8 },
2038     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i32, 10 },
2039     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i64, 10 },
2040     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i64, 18 },
2041     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i64,  5 },
2042     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i64, 10 },
2043 
2044     { ISD::FP_TO_SINT,  MVT::v16i8,  MVT::v8f32,  2 },
2045     { ISD::FP_TO_SINT,  MVT::v16i8,  MVT::v4f64,  2 },
2046     { ISD::FP_TO_SINT,  MVT::v32i8,  MVT::v8f32,  2 },
2047     { ISD::FP_TO_SINT,  MVT::v32i8,  MVT::v4f64,  2 },
2048     { ISD::FP_TO_SINT,  MVT::v8i16,  MVT::v8f32,  2 },
2049     { ISD::FP_TO_SINT,  MVT::v8i16,  MVT::v4f64,  2 },
2050     { ISD::FP_TO_SINT,  MVT::v16i16, MVT::v8f32,  2 },
2051     { ISD::FP_TO_SINT,  MVT::v16i16, MVT::v4f64,  2 },
2052     { ISD::FP_TO_SINT,  MVT::v4i32,  MVT::v4f64,  2 },
2053     { ISD::FP_TO_SINT,  MVT::v8i32,  MVT::v8f32,  2 },
2054     { ISD::FP_TO_SINT,  MVT::v8i32,  MVT::v8f64,  5 },
2055 
2056     { ISD::FP_TO_UINT,  MVT::v16i8,  MVT::v8f32,  2 },
2057     { ISD::FP_TO_UINT,  MVT::v16i8,  MVT::v4f64,  2 },
2058     { ISD::FP_TO_UINT,  MVT::v32i8,  MVT::v8f32,  2 },
2059     { ISD::FP_TO_UINT,  MVT::v32i8,  MVT::v4f64,  2 },
2060     { ISD::FP_TO_UINT,  MVT::v8i16,  MVT::v8f32,  2 },
2061     { ISD::FP_TO_UINT,  MVT::v8i16,  MVT::v4f64,  2 },
2062     { ISD::FP_TO_UINT,  MVT::v16i16, MVT::v8f32,  2 },
2063     { ISD::FP_TO_UINT,  MVT::v16i16, MVT::v4f64,  2 },
2064     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v4f32,  3 },
2065     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v2f64,  4 },
2066     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v4f64,  6 },
2067     { ISD::FP_TO_UINT,  MVT::v8i32,  MVT::v8f32,  7 },
2068     { ISD::FP_TO_UINT,  MVT::v8i32,  MVT::v4f64,  7 },
2069 
2070     { ISD::FP_EXTEND,   MVT::v4f64,  MVT::v4f32,  1 },
2071     { ISD::FP_ROUND,    MVT::v4f32,  MVT::v4f64,  1 },
2072   };
2073 
2074   static const TypeConversionCostTblEntry SSE41ConversionTbl[] = {
2075     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v16i8,   1 },
2076     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v16i8,   1 },
2077     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v16i8,   1 },
2078     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v16i8,   1 },
2079     { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v16i8,   1 },
2080     { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v16i8,   1 },
2081     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v8i16,   1 },
2082     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v8i16,   1 },
2083     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v8i16,   1 },
2084     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v8i16,   1 },
2085     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v4i32,   1 },
2086     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v4i32,   1 },
2087 
2088     // These truncates end up widening elements.
2089     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i8,   1 }, // PMOVXZBQ
2090     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i16,  1 }, // PMOVXZWQ
2091     { ISD::TRUNCATE,    MVT::v4i1,   MVT::v4i8,   1 }, // PMOVXZBD
2092 
2093     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v4i32,  2 },
2094     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v4i32,  2 },
2095     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v2i64,  2 },
2096 
2097     { ISD::SINT_TO_FP,  MVT::f32,    MVT::i32,    1 },
2098     { ISD::SINT_TO_FP,  MVT::f64,    MVT::i32,    1 },
2099     { ISD::SINT_TO_FP,  MVT::f32,    MVT::i64,    1 },
2100     { ISD::SINT_TO_FP,  MVT::f64,    MVT::i64,    1 },
2101     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v16i8,  1 },
2102     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v16i8,  1 },
2103     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v8i16,  1 },
2104     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v8i16,  1 },
2105     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v4i32,  1 },
2106     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v4i32,  1 },
2107     { ISD::SINT_TO_FP,  MVT::v4f64,  MVT::v4i32,  2 },
2108 
2109     { ISD::UINT_TO_FP,  MVT::f32,    MVT::i32,    1 },
2110     { ISD::UINT_TO_FP,  MVT::f64,    MVT::i32,    1 },
2111     { ISD::UINT_TO_FP,  MVT::f32,    MVT::i64,    4 },
2112     { ISD::UINT_TO_FP,  MVT::f64,    MVT::i64,    4 },
2113     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v16i8,  1 },
2114     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v16i8,  1 },
2115     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v8i16,  1 },
2116     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v8i16,  1 },
2117     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i32,  3 },
2118     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i32,  3 },
2119     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v4i32,  2 },
2120     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v2i64, 12 },
2121     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i64, 22 },
2122     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i64,  4 },
2123 
2124     { ISD::FP_TO_SINT,  MVT::i32,    MVT::f32,    1 },
2125     { ISD::FP_TO_SINT,  MVT::i64,    MVT::f32,    1 },
2126     { ISD::FP_TO_SINT,  MVT::i32,    MVT::f64,    1 },
2127     { ISD::FP_TO_SINT,  MVT::i64,    MVT::f64,    1 },
2128     { ISD::FP_TO_SINT,  MVT::v16i8,  MVT::v4f32,  2 },
2129     { ISD::FP_TO_SINT,  MVT::v16i8,  MVT::v2f64,  2 },
2130     { ISD::FP_TO_SINT,  MVT::v8i16,  MVT::v4f32,  1 },
2131     { ISD::FP_TO_SINT,  MVT::v8i16,  MVT::v2f64,  1 },
2132     { ISD::FP_TO_SINT,  MVT::v4i32,  MVT::v4f32,  1 },
2133     { ISD::FP_TO_SINT,  MVT::v4i32,  MVT::v2f64,  1 },
2134 
2135     { ISD::FP_TO_UINT,  MVT::i32,    MVT::f32,    1 },
2136     { ISD::FP_TO_UINT,  MVT::i64,    MVT::f32,    4 },
2137     { ISD::FP_TO_UINT,  MVT::i32,    MVT::f64,    1 },
2138     { ISD::FP_TO_UINT,  MVT::i64,    MVT::f64,    4 },
2139     { ISD::FP_TO_UINT,  MVT::v16i8,  MVT::v4f32,  2 },
2140     { ISD::FP_TO_UINT,  MVT::v16i8,  MVT::v2f64,  2 },
2141     { ISD::FP_TO_UINT,  MVT::v8i16,  MVT::v4f32,  1 },
2142     { ISD::FP_TO_UINT,  MVT::v8i16,  MVT::v2f64,  1 },
2143     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v4f32,  4 },
2144     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v2f64,  4 },
2145   };
2146 
2147   static const TypeConversionCostTblEntry SSE2ConversionTbl[] = {
2148     // These are somewhat magic numbers justified by comparing the
2149     // output of llvm-mca for our various supported scheduler models
2150     // and basing it off the worst case scenario.
2151     { ISD::SINT_TO_FP,  MVT::f32,    MVT::i32,    3 },
2152     { ISD::SINT_TO_FP,  MVT::f64,    MVT::i32,    3 },
2153     { ISD::SINT_TO_FP,  MVT::f32,    MVT::i64,    3 },
2154     { ISD::SINT_TO_FP,  MVT::f64,    MVT::i64,    3 },
2155     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v16i8,  3 },
2156     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v16i8,  4 },
2157     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v8i16,  3 },
2158     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v8i16,  4 },
2159     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v4i32,  3 },
2160     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v4i32,  4 },
2161     { ISD::SINT_TO_FP,  MVT::v4f32,  MVT::v2i64,  8 },
2162     { ISD::SINT_TO_FP,  MVT::v2f64,  MVT::v2i64,  8 },
2163 
2164     { ISD::UINT_TO_FP,  MVT::f32,    MVT::i32,    3 },
2165     { ISD::UINT_TO_FP,  MVT::f64,    MVT::i32,    3 },
2166     { ISD::UINT_TO_FP,  MVT::f32,    MVT::i64,    8 },
2167     { ISD::UINT_TO_FP,  MVT::f64,    MVT::i64,    9 },
2168     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v16i8,  4 },
2169     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v16i8,  4 },
2170     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v8i16,  4 },
2171     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v8i16,  4 },
2172     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i32,  7 },
2173     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v4i32,  7 },
2174     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i32,  5 },
2175     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i64, 15 },
2176     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v2i64, 18 },
2177 
2178     { ISD::FP_TO_SINT,  MVT::i32,    MVT::f32,    4 },
2179     { ISD::FP_TO_SINT,  MVT::i64,    MVT::f32,    4 },
2180     { ISD::FP_TO_SINT,  MVT::i32,    MVT::f64,    4 },
2181     { ISD::FP_TO_SINT,  MVT::i64,    MVT::f64,    4 },
2182     { ISD::FP_TO_SINT,  MVT::v16i8,  MVT::v4f32,  6 },
2183     { ISD::FP_TO_SINT,  MVT::v16i8,  MVT::v2f64,  6 },
2184     { ISD::FP_TO_SINT,  MVT::v8i16,  MVT::v4f32,  5 },
2185     { ISD::FP_TO_SINT,  MVT::v8i16,  MVT::v2f64,  5 },
2186     { ISD::FP_TO_SINT,  MVT::v4i32,  MVT::v4f32,  4 },
2187     { ISD::FP_TO_SINT,  MVT::v4i32,  MVT::v2f64,  4 },
2188 
2189     { ISD::FP_TO_UINT,  MVT::i32,    MVT::f32,    4 },
2190     { ISD::FP_TO_UINT,  MVT::i64,    MVT::f32,    4 },
2191     { ISD::FP_TO_UINT,  MVT::i32,    MVT::f64,    4 },
2192     { ISD::FP_TO_UINT,  MVT::i64,    MVT::f64,   15 },
2193     { ISD::FP_TO_UINT,  MVT::v16i8,  MVT::v4f32,  6 },
2194     { ISD::FP_TO_UINT,  MVT::v16i8,  MVT::v2f64,  6 },
2195     { ISD::FP_TO_UINT,  MVT::v8i16,  MVT::v4f32,  5 },
2196     { ISD::FP_TO_UINT,  MVT::v8i16,  MVT::v2f64,  5 },
2197     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v4f32,  8 },
2198     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v2f64,  8 },
2199 
2200     { ISD::ZERO_EXTEND, MVT::v2i64,  MVT::v16i8,  4 },
2201     { ISD::SIGN_EXTEND, MVT::v2i64,  MVT::v16i8,  4 },
2202     { ISD::ZERO_EXTEND, MVT::v4i32,  MVT::v16i8,  2 },
2203     { ISD::SIGN_EXTEND, MVT::v4i32,  MVT::v16i8,  3 },
2204     { ISD::ZERO_EXTEND, MVT::v8i16,  MVT::v16i8,  1 },
2205     { ISD::SIGN_EXTEND, MVT::v8i16,  MVT::v16i8,  2 },
2206     { ISD::ZERO_EXTEND, MVT::v2i64,  MVT::v8i16,  2 },
2207     { ISD::SIGN_EXTEND, MVT::v2i64,  MVT::v8i16,  3 },
2208     { ISD::ZERO_EXTEND, MVT::v4i32,  MVT::v8i16,  1 },
2209     { ISD::SIGN_EXTEND, MVT::v4i32,  MVT::v8i16,  2 },
2210     { ISD::ZERO_EXTEND, MVT::v2i64,  MVT::v4i32,  1 },
2211     { ISD::SIGN_EXTEND, MVT::v2i64,  MVT::v4i32,  2 },
2212 
2213     // These truncates are really widening elements.
2214     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i32,  1 }, // PSHUFD
2215     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i16,  2 }, // PUNPCKLWD+DQ
2216     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i8,   3 }, // PUNPCKLBW+WD+PSHUFD
2217     { ISD::TRUNCATE,    MVT::v4i1,   MVT::v4i16,  1 }, // PUNPCKLWD
2218     { ISD::TRUNCATE,    MVT::v4i1,   MVT::v4i8,   2 }, // PUNPCKLBW+WD
2219     { ISD::TRUNCATE,    MVT::v8i1,   MVT::v8i8,   1 }, // PUNPCKLBW
2220 
2221     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v8i16,  2 }, // PAND+PACKUSWB
2222     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v16i16, 3 },
2223     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v4i32,  3 }, // PAND+2*PACKUSWB
2224     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v16i32, 7 },
2225     { ISD::TRUNCATE,    MVT::v2i16,  MVT::v2i32,  1 },
2226     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v4i32,  3 },
2227     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v8i32,  5 },
2228     { ISD::TRUNCATE,    MVT::v16i16, MVT::v16i32,10 },
2229     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v2i64,  4 }, // PAND+3*PACKUSWB
2230     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v2i64,  2 }, // PSHUFD+PSHUFLW
2231     { ISD::TRUNCATE,    MVT::v4i32,  MVT::v2i64,  1 }, // PSHUFD
2232   };
2233 
2234   // Attempt to map directly to (simple) MVT types to let us match custom entries.
2235   EVT SrcTy = TLI->getValueType(DL, Src);
2236   EVT DstTy = TLI->getValueType(DL, Dst);
2237 
2238   // The function getSimpleVT only handles simple value types.
2239   if (SrcTy.isSimple() && DstTy.isSimple()) {
2240     MVT SimpleSrcTy = SrcTy.getSimpleVT();
2241     MVT SimpleDstTy = DstTy.getSimpleVT();
2242 
2243     if (ST->useAVX512Regs()) {
2244       if (ST->hasBWI())
2245         if (const auto *Entry = ConvertCostTableLookup(
2246                 AVX512BWConversionTbl, ISD, SimpleDstTy, SimpleSrcTy))
2247           return AdjustCost(Entry->Cost);
2248 
2249       if (ST->hasDQI())
2250         if (const auto *Entry = ConvertCostTableLookup(
2251                 AVX512DQConversionTbl, ISD, SimpleDstTy, SimpleSrcTy))
2252           return AdjustCost(Entry->Cost);
2253 
2254       if (ST->hasAVX512())
2255         if (const auto *Entry = ConvertCostTableLookup(
2256                 AVX512FConversionTbl, ISD, SimpleDstTy, SimpleSrcTy))
2257           return AdjustCost(Entry->Cost);
2258     }
2259 
2260     if (ST->hasBWI())
2261       if (const auto *Entry = ConvertCostTableLookup(
2262               AVX512BWVLConversionTbl, ISD, SimpleDstTy, SimpleSrcTy))
2263         return AdjustCost(Entry->Cost);
2264 
2265     if (ST->hasDQI())
2266       if (const auto *Entry = ConvertCostTableLookup(
2267               AVX512DQVLConversionTbl, ISD, SimpleDstTy, SimpleSrcTy))
2268         return AdjustCost(Entry->Cost);
2269 
2270     if (ST->hasAVX512())
2271       if (const auto *Entry = ConvertCostTableLookup(AVX512VLConversionTbl, ISD,
2272                                                      SimpleDstTy, SimpleSrcTy))
2273         return AdjustCost(Entry->Cost);
2274 
2275     if (ST->hasAVX2()) {
2276       if (const auto *Entry = ConvertCostTableLookup(AVX2ConversionTbl, ISD,
2277                                                      SimpleDstTy, SimpleSrcTy))
2278         return AdjustCost(Entry->Cost);
2279     }
2280 
2281     if (ST->hasAVX()) {
2282       if (const auto *Entry = ConvertCostTableLookup(AVXConversionTbl, ISD,
2283                                                      SimpleDstTy, SimpleSrcTy))
2284         return AdjustCost(Entry->Cost);
2285     }
2286 
2287     if (ST->hasSSE41()) {
2288       if (const auto *Entry = ConvertCostTableLookup(SSE41ConversionTbl, ISD,
2289                                                      SimpleDstTy, SimpleSrcTy))
2290         return AdjustCost(Entry->Cost);
2291     }
2292 
2293     if (ST->hasSSE2()) {
2294       if (const auto *Entry = ConvertCostTableLookup(SSE2ConversionTbl, ISD,
2295                                                      SimpleDstTy, SimpleSrcTy))
2296         return AdjustCost(Entry->Cost);
2297     }
2298   }
2299 
2300   // Fall back to legalized types.
2301   std::pair<InstructionCost, MVT> LTSrc = TLI->getTypeLegalizationCost(DL, Src);
2302   std::pair<InstructionCost, MVT> LTDest =
2303       TLI->getTypeLegalizationCost(DL, Dst);
2304 
2305   if (ST->useAVX512Regs()) {
2306     if (ST->hasBWI())
2307       if (const auto *Entry = ConvertCostTableLookup(
2308               AVX512BWConversionTbl, ISD, LTDest.second, LTSrc.second))
2309         return AdjustCost(std::max(LTSrc.first, LTDest.first) * Entry->Cost);
2310 
2311     if (ST->hasDQI())
2312       if (const auto *Entry = ConvertCostTableLookup(
2313               AVX512DQConversionTbl, ISD, LTDest.second, LTSrc.second))
2314         return AdjustCost(std::max(LTSrc.first, LTDest.first) * Entry->Cost);
2315 
2316     if (ST->hasAVX512())
2317       if (const auto *Entry = ConvertCostTableLookup(
2318               AVX512FConversionTbl, ISD, LTDest.second, LTSrc.second))
2319         return AdjustCost(std::max(LTSrc.first, LTDest.first) * Entry->Cost);
2320   }
2321 
2322   if (ST->hasBWI())
2323     if (const auto *Entry = ConvertCostTableLookup(AVX512BWVLConversionTbl, ISD,
2324                                                    LTDest.second, LTSrc.second))
2325       return AdjustCost(std::max(LTSrc.first, LTDest.first) * Entry->Cost);
2326 
2327   if (ST->hasDQI())
2328     if (const auto *Entry = ConvertCostTableLookup(AVX512DQVLConversionTbl, ISD,
2329                                                    LTDest.second, LTSrc.second))
2330       return AdjustCost(std::max(LTSrc.first, LTDest.first) * Entry->Cost);
2331 
2332   if (ST->hasAVX512())
2333     if (const auto *Entry = ConvertCostTableLookup(AVX512VLConversionTbl, ISD,
2334                                                    LTDest.second, LTSrc.second))
2335       return AdjustCost(std::max(LTSrc.first, LTDest.first) * Entry->Cost);
2336 
2337   if (ST->hasAVX2())
2338     if (const auto *Entry = ConvertCostTableLookup(AVX2ConversionTbl, ISD,
2339                                                    LTDest.second, LTSrc.second))
2340       return AdjustCost(std::max(LTSrc.first, LTDest.first) * Entry->Cost);
2341 
2342   if (ST->hasAVX())
2343     if (const auto *Entry = ConvertCostTableLookup(AVXConversionTbl, ISD,
2344                                                    LTDest.second, LTSrc.second))
2345       return AdjustCost(std::max(LTSrc.first, LTDest.first) * Entry->Cost);
2346 
2347   if (ST->hasSSE41())
2348     if (const auto *Entry = ConvertCostTableLookup(SSE41ConversionTbl, ISD,
2349                                                    LTDest.second, LTSrc.second))
2350       return AdjustCost(std::max(LTSrc.first, LTDest.first) * Entry->Cost);
2351 
2352   if (ST->hasSSE2())
2353     if (const auto *Entry = ConvertCostTableLookup(SSE2ConversionTbl, ISD,
2354                                                    LTDest.second, LTSrc.second))
2355       return AdjustCost(std::max(LTSrc.first, LTDest.first) * Entry->Cost);
2356 
2357   // Fallback, for i8/i16 sitofp/uitofp cases we need to extend to i32 for
2358   // sitofp.
2359   if ((ISD == ISD::SINT_TO_FP || ISD == ISD::UINT_TO_FP) &&
2360       1 < Src->getScalarSizeInBits() && Src->getScalarSizeInBits() < 32) {
2361     Type *ExtSrc = Src->getWithNewBitWidth(32);
2362     unsigned ExtOpc =
2363         (ISD == ISD::SINT_TO_FP) ? Instruction::SExt : Instruction::ZExt;
2364 
2365     // For scalar loads the extend would be free.
2366     InstructionCost ExtCost = 0;
2367     if (!(Src->isIntegerTy() && I && isa<LoadInst>(I->getOperand(0))))
2368       ExtCost = getCastInstrCost(ExtOpc, ExtSrc, Src, CCH, CostKind);
2369 
2370     return ExtCost + getCastInstrCost(Instruction::SIToFP, Dst, ExtSrc,
2371                                       TTI::CastContextHint::None, CostKind);
2372   }
2373 
2374   // Fallback for fptosi/fptoui i8/i16 cases we need to truncate from fptosi
2375   // i32.
2376   if ((ISD == ISD::FP_TO_SINT || ISD == ISD::FP_TO_UINT) &&
2377       1 < Dst->getScalarSizeInBits() && Dst->getScalarSizeInBits() < 32) {
2378     Type *TruncDst = Dst->getWithNewBitWidth(32);
2379     return getCastInstrCost(Instruction::FPToSI, TruncDst, Src, CCH, CostKind) +
2380            getCastInstrCost(Instruction::Trunc, Dst, TruncDst,
2381                             TTI::CastContextHint::None, CostKind);
2382   }
2383 
2384   return AdjustCost(
2385       BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
2386 }
2387 
2388 InstructionCost X86TTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
2389                                                Type *CondTy,
2390                                                CmpInst::Predicate VecPred,
2391                                                TTI::TargetCostKind CostKind,
2392                                                const Instruction *I) {
2393   // TODO: Handle other cost kinds.
2394   if (CostKind != TTI::TCK_RecipThroughput)
2395     return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind,
2396                                      I);
2397 
2398   // Legalize the type.
2399   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
2400 
2401   MVT MTy = LT.second;
2402 
2403   int ISD = TLI->InstructionOpcodeToISD(Opcode);
2404   assert(ISD && "Invalid opcode");
2405 
2406   unsigned ExtraCost = 0;
2407   if (I && (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp)) {
2408     // Some vector comparison predicates cost extra instructions.
2409     if (MTy.isVector() &&
2410         !((ST->hasXOP() && (!ST->hasAVX2() || MTy.is128BitVector())) ||
2411           (ST->hasAVX512() && 32 <= MTy.getScalarSizeInBits()) ||
2412           ST->hasBWI())) {
2413       switch (cast<CmpInst>(I)->getPredicate()) {
2414       case CmpInst::Predicate::ICMP_NE:
2415         // xor(cmpeq(x,y),-1)
2416         ExtraCost = 1;
2417         break;
2418       case CmpInst::Predicate::ICMP_SGE:
2419       case CmpInst::Predicate::ICMP_SLE:
2420         // xor(cmpgt(x,y),-1)
2421         ExtraCost = 1;
2422         break;
2423       case CmpInst::Predicate::ICMP_ULT:
2424       case CmpInst::Predicate::ICMP_UGT:
2425         // cmpgt(xor(x,signbit),xor(y,signbit))
2426         // xor(cmpeq(pmaxu(x,y),x),-1)
2427         ExtraCost = 2;
2428         break;
2429       case CmpInst::Predicate::ICMP_ULE:
2430       case CmpInst::Predicate::ICMP_UGE:
2431         if ((ST->hasSSE41() && MTy.getScalarSizeInBits() == 32) ||
2432             (ST->hasSSE2() && MTy.getScalarSizeInBits() < 32)) {
2433           // cmpeq(psubus(x,y),0)
2434           // cmpeq(pminu(x,y),x)
2435           ExtraCost = 1;
2436         } else {
2437           // xor(cmpgt(xor(x,signbit),xor(y,signbit)),-1)
2438           ExtraCost = 3;
2439         }
2440         break;
2441       default:
2442         break;
2443       }
2444     }
2445   }
2446 
2447   static const CostTblEntry SLMCostTbl[] = {
2448     // slm pcmpeq/pcmpgt throughput is 2
2449     { ISD::SETCC,   MVT::v2i64,   2 },
2450   };
2451 
2452   static const CostTblEntry AVX512BWCostTbl[] = {
2453     { ISD::SETCC,   MVT::v32i16,  1 },
2454     { ISD::SETCC,   MVT::v64i8,   1 },
2455 
2456     { ISD::SELECT,  MVT::v32i16,  1 },
2457     { ISD::SELECT,  MVT::v64i8,   1 },
2458   };
2459 
2460   static const CostTblEntry AVX512CostTbl[] = {
2461     { ISD::SETCC,   MVT::v8i64,   1 },
2462     { ISD::SETCC,   MVT::v16i32,  1 },
2463     { ISD::SETCC,   MVT::v8f64,   1 },
2464     { ISD::SETCC,   MVT::v16f32,  1 },
2465 
2466     { ISD::SELECT,  MVT::v8i64,   1 },
2467     { ISD::SELECT,  MVT::v16i32,  1 },
2468     { ISD::SELECT,  MVT::v8f64,   1 },
2469     { ISD::SELECT,  MVT::v16f32,  1 },
2470 
2471     { ISD::SETCC,   MVT::v32i16,  2 }, // FIXME: should probably be 4
2472     { ISD::SETCC,   MVT::v64i8,   2 }, // FIXME: should probably be 4
2473 
2474     { ISD::SELECT,  MVT::v32i16,  2 }, // FIXME: should be 3
2475     { ISD::SELECT,  MVT::v64i8,   2 }, // FIXME: should be 3
2476   };
2477 
2478   static const CostTblEntry AVX2CostTbl[] = {
2479     { ISD::SETCC,   MVT::v4i64,   1 },
2480     { ISD::SETCC,   MVT::v8i32,   1 },
2481     { ISD::SETCC,   MVT::v16i16,  1 },
2482     { ISD::SETCC,   MVT::v32i8,   1 },
2483 
2484     { ISD::SELECT,  MVT::v4i64,   1 }, // pblendvb
2485     { ISD::SELECT,  MVT::v8i32,   1 }, // pblendvb
2486     { ISD::SELECT,  MVT::v16i16,  1 }, // pblendvb
2487     { ISD::SELECT,  MVT::v32i8,   1 }, // pblendvb
2488   };
2489 
2490   static const CostTblEntry AVX1CostTbl[] = {
2491     { ISD::SETCC,   MVT::v4f64,   1 },
2492     { ISD::SETCC,   MVT::v8f32,   1 },
2493     // AVX1 does not support 8-wide integer compare.
2494     { ISD::SETCC,   MVT::v4i64,   4 },
2495     { ISD::SETCC,   MVT::v8i32,   4 },
2496     { ISD::SETCC,   MVT::v16i16,  4 },
2497     { ISD::SETCC,   MVT::v32i8,   4 },
2498 
2499     { ISD::SELECT,  MVT::v4f64,   1 }, // vblendvpd
2500     { ISD::SELECT,  MVT::v8f32,   1 }, // vblendvps
2501     { ISD::SELECT,  MVT::v4i64,   1 }, // vblendvpd
2502     { ISD::SELECT,  MVT::v8i32,   1 }, // vblendvps
2503     { ISD::SELECT,  MVT::v16i16,  3 }, // vandps + vandnps + vorps
2504     { ISD::SELECT,  MVT::v32i8,   3 }, // vandps + vandnps + vorps
2505   };
2506 
2507   static const CostTblEntry SSE42CostTbl[] = {
2508     { ISD::SETCC,   MVT::v2f64,   1 },
2509     { ISD::SETCC,   MVT::v4f32,   1 },
2510     { ISD::SETCC,   MVT::v2i64,   1 },
2511   };
2512 
2513   static const CostTblEntry SSE41CostTbl[] = {
2514     { ISD::SELECT,  MVT::v2f64,   1 }, // blendvpd
2515     { ISD::SELECT,  MVT::v4f32,   1 }, // blendvps
2516     { ISD::SELECT,  MVT::v2i64,   1 }, // pblendvb
2517     { ISD::SELECT,  MVT::v4i32,   1 }, // pblendvb
2518     { ISD::SELECT,  MVT::v8i16,   1 }, // pblendvb
2519     { ISD::SELECT,  MVT::v16i8,   1 }, // pblendvb
2520   };
2521 
2522   static const CostTblEntry SSE2CostTbl[] = {
2523     { ISD::SETCC,   MVT::v2f64,   2 },
2524     { ISD::SETCC,   MVT::f64,     1 },
2525     { ISD::SETCC,   MVT::v2i64,   8 },
2526     { ISD::SETCC,   MVT::v4i32,   1 },
2527     { ISD::SETCC,   MVT::v8i16,   1 },
2528     { ISD::SETCC,   MVT::v16i8,   1 },
2529 
2530     { ISD::SELECT,  MVT::v2f64,   3 }, // andpd + andnpd + orpd
2531     { ISD::SELECT,  MVT::v2i64,   3 }, // pand + pandn + por
2532     { ISD::SELECT,  MVT::v4i32,   3 }, // pand + pandn + por
2533     { ISD::SELECT,  MVT::v8i16,   3 }, // pand + pandn + por
2534     { ISD::SELECT,  MVT::v16i8,   3 }, // pand + pandn + por
2535   };
2536 
2537   static const CostTblEntry SSE1CostTbl[] = {
2538     { ISD::SETCC,   MVT::v4f32,   2 },
2539     { ISD::SETCC,   MVT::f32,     1 },
2540 
2541     { ISD::SELECT,  MVT::v4f32,   3 }, // andps + andnps + orps
2542   };
2543 
2544   if (ST->isSLM())
2545     if (const auto *Entry = CostTableLookup(SLMCostTbl, ISD, MTy))
2546       return LT.first * (ExtraCost + Entry->Cost);
2547 
2548   if (ST->hasBWI())
2549     if (const auto *Entry = CostTableLookup(AVX512BWCostTbl, ISD, MTy))
2550       return LT.first * (ExtraCost + Entry->Cost);
2551 
2552   if (ST->hasAVX512())
2553     if (const auto *Entry = CostTableLookup(AVX512CostTbl, ISD, MTy))
2554       return LT.first * (ExtraCost + Entry->Cost);
2555 
2556   if (ST->hasAVX2())
2557     if (const auto *Entry = CostTableLookup(AVX2CostTbl, ISD, MTy))
2558       return LT.first * (ExtraCost + Entry->Cost);
2559 
2560   if (ST->hasAVX())
2561     if (const auto *Entry = CostTableLookup(AVX1CostTbl, ISD, MTy))
2562       return LT.first * (ExtraCost + Entry->Cost);
2563 
2564   if (ST->hasSSE42())
2565     if (const auto *Entry = CostTableLookup(SSE42CostTbl, ISD, MTy))
2566       return LT.first * (ExtraCost + Entry->Cost);
2567 
2568   if (ST->hasSSE41())
2569     if (const auto *Entry = CostTableLookup(SSE41CostTbl, ISD, MTy))
2570       return LT.first * (ExtraCost + Entry->Cost);
2571 
2572   if (ST->hasSSE2())
2573     if (const auto *Entry = CostTableLookup(SSE2CostTbl, ISD, MTy))
2574       return LT.first * (ExtraCost + Entry->Cost);
2575 
2576   if (ST->hasSSE1())
2577     if (const auto *Entry = CostTableLookup(SSE1CostTbl, ISD, MTy))
2578       return LT.first * (ExtraCost + Entry->Cost);
2579 
2580   return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I);
2581 }
2582 
2583 unsigned X86TTIImpl::getAtomicMemIntrinsicMaxElementSize() const { return 16; }
2584 
2585 InstructionCost
2586 X86TTIImpl::getTypeBasedIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
2587                                            TTI::TargetCostKind CostKind) {
2588 
2589   // Costs should match the codegen from:
2590   // BITREVERSE: llvm\test\CodeGen\X86\vector-bitreverse.ll
2591   // BSWAP: llvm\test\CodeGen\X86\bswap-vector.ll
2592   // CTLZ: llvm\test\CodeGen\X86\vector-lzcnt-*.ll
2593   // CTPOP: llvm\test\CodeGen\X86\vector-popcnt-*.ll
2594   // CTTZ: llvm\test\CodeGen\X86\vector-tzcnt-*.ll
2595 
2596   // TODO: Overflow intrinsics (*ADDO, *SUBO, *MULO) with vector types are not
2597   //       specialized in these tables yet.
2598   static const CostTblEntry AVX512BITALGCostTbl[] = {
2599     { ISD::CTPOP,      MVT::v32i16,  1 },
2600     { ISD::CTPOP,      MVT::v64i8,   1 },
2601     { ISD::CTPOP,      MVT::v16i16,  1 },
2602     { ISD::CTPOP,      MVT::v32i8,   1 },
2603     { ISD::CTPOP,      MVT::v8i16,   1 },
2604     { ISD::CTPOP,      MVT::v16i8,   1 },
2605   };
2606   static const CostTblEntry AVX512VPOPCNTDQCostTbl[] = {
2607     { ISD::CTPOP,      MVT::v8i64,   1 },
2608     { ISD::CTPOP,      MVT::v16i32,  1 },
2609     { ISD::CTPOP,      MVT::v4i64,   1 },
2610     { ISD::CTPOP,      MVT::v8i32,   1 },
2611     { ISD::CTPOP,      MVT::v2i64,   1 },
2612     { ISD::CTPOP,      MVT::v4i32,   1 },
2613   };
2614   static const CostTblEntry AVX512CDCostTbl[] = {
2615     { ISD::CTLZ,       MVT::v8i64,   1 },
2616     { ISD::CTLZ,       MVT::v16i32,  1 },
2617     { ISD::CTLZ,       MVT::v32i16,  8 },
2618     { ISD::CTLZ,       MVT::v64i8,  20 },
2619     { ISD::CTLZ,       MVT::v4i64,   1 },
2620     { ISD::CTLZ,       MVT::v8i32,   1 },
2621     { ISD::CTLZ,       MVT::v16i16,  4 },
2622     { ISD::CTLZ,       MVT::v32i8,  10 },
2623     { ISD::CTLZ,       MVT::v2i64,   1 },
2624     { ISD::CTLZ,       MVT::v4i32,   1 },
2625     { ISD::CTLZ,       MVT::v8i16,   4 },
2626     { ISD::CTLZ,       MVT::v16i8,   4 },
2627   };
2628   static const CostTblEntry AVX512BWCostTbl[] = {
2629     { ISD::ABS,        MVT::v32i16,  1 },
2630     { ISD::ABS,        MVT::v64i8,   1 },
2631     { ISD::BITREVERSE, MVT::v8i64,   5 },
2632     { ISD::BITREVERSE, MVT::v16i32,  5 },
2633     { ISD::BITREVERSE, MVT::v32i16,  5 },
2634     { ISD::BITREVERSE, MVT::v64i8,   5 },
2635     { ISD::BSWAP,      MVT::v8i64,   1 },
2636     { ISD::BSWAP,      MVT::v16i32,  1 },
2637     { ISD::BSWAP,      MVT::v32i16,  1 },
2638     { ISD::CTLZ,       MVT::v8i64,  23 },
2639     { ISD::CTLZ,       MVT::v16i32, 22 },
2640     { ISD::CTLZ,       MVT::v32i16, 18 },
2641     { ISD::CTLZ,       MVT::v64i8,  17 },
2642     { ISD::CTPOP,      MVT::v8i64,   7 },
2643     { ISD::CTPOP,      MVT::v16i32, 11 },
2644     { ISD::CTPOP,      MVT::v32i16,  9 },
2645     { ISD::CTPOP,      MVT::v64i8,   6 },
2646     { ISD::CTTZ,       MVT::v8i64,  10 },
2647     { ISD::CTTZ,       MVT::v16i32, 14 },
2648     { ISD::CTTZ,       MVT::v32i16, 12 },
2649     { ISD::CTTZ,       MVT::v64i8,   9 },
2650     { ISD::SADDSAT,    MVT::v32i16,  1 },
2651     { ISD::SADDSAT,    MVT::v64i8,   1 },
2652     { ISD::SMAX,       MVT::v32i16,  1 },
2653     { ISD::SMAX,       MVT::v64i8,   1 },
2654     { ISD::SMIN,       MVT::v32i16,  1 },
2655     { ISD::SMIN,       MVT::v64i8,   1 },
2656     { ISD::SSUBSAT,    MVT::v32i16,  1 },
2657     { ISD::SSUBSAT,    MVT::v64i8,   1 },
2658     { ISD::UADDSAT,    MVT::v32i16,  1 },
2659     { ISD::UADDSAT,    MVT::v64i8,   1 },
2660     { ISD::UMAX,       MVT::v32i16,  1 },
2661     { ISD::UMAX,       MVT::v64i8,   1 },
2662     { ISD::UMIN,       MVT::v32i16,  1 },
2663     { ISD::UMIN,       MVT::v64i8,   1 },
2664     { ISD::USUBSAT,    MVT::v32i16,  1 },
2665     { ISD::USUBSAT,    MVT::v64i8,   1 },
2666   };
2667   static const CostTblEntry AVX512CostTbl[] = {
2668     { ISD::ABS,        MVT::v8i64,   1 },
2669     { ISD::ABS,        MVT::v16i32,  1 },
2670     { ISD::ABS,        MVT::v32i16,  2 }, // FIXME: include split
2671     { ISD::ABS,        MVT::v64i8,   2 }, // FIXME: include split
2672     { ISD::ABS,        MVT::v4i64,   1 },
2673     { ISD::ABS,        MVT::v2i64,   1 },
2674     { ISD::BITREVERSE, MVT::v8i64,  36 },
2675     { ISD::BITREVERSE, MVT::v16i32, 24 },
2676     { ISD::BITREVERSE, MVT::v32i16, 10 },
2677     { ISD::BITREVERSE, MVT::v64i8,  10 },
2678     { ISD::BSWAP,      MVT::v8i64,   4 },
2679     { ISD::BSWAP,      MVT::v16i32,  4 },
2680     { ISD::BSWAP,      MVT::v32i16,  4 },
2681     { ISD::CTLZ,       MVT::v8i64,  29 },
2682     { ISD::CTLZ,       MVT::v16i32, 35 },
2683     { ISD::CTLZ,       MVT::v32i16, 28 },
2684     { ISD::CTLZ,       MVT::v64i8,  18 },
2685     { ISD::CTPOP,      MVT::v8i64,  16 },
2686     { ISD::CTPOP,      MVT::v16i32, 24 },
2687     { ISD::CTPOP,      MVT::v32i16, 18 },
2688     { ISD::CTPOP,      MVT::v64i8,  12 },
2689     { ISD::CTTZ,       MVT::v8i64,  20 },
2690     { ISD::CTTZ,       MVT::v16i32, 28 },
2691     { ISD::CTTZ,       MVT::v32i16, 24 },
2692     { ISD::CTTZ,       MVT::v64i8,  18 },
2693     { ISD::SMAX,       MVT::v8i64,   1 },
2694     { ISD::SMAX,       MVT::v16i32,  1 },
2695     { ISD::SMAX,       MVT::v32i16,  2 }, // FIXME: include split
2696     { ISD::SMAX,       MVT::v64i8,   2 }, // FIXME: include split
2697     { ISD::SMAX,       MVT::v4i64,   1 },
2698     { ISD::SMAX,       MVT::v2i64,   1 },
2699     { ISD::SMIN,       MVT::v8i64,   1 },
2700     { ISD::SMIN,       MVT::v16i32,  1 },
2701     { ISD::SMIN,       MVT::v32i16,  2 }, // FIXME: include split
2702     { ISD::SMIN,       MVT::v64i8,   2 }, // FIXME: include split
2703     { ISD::SMIN,       MVT::v4i64,   1 },
2704     { ISD::SMIN,       MVT::v2i64,   1 },
2705     { ISD::UMAX,       MVT::v8i64,   1 },
2706     { ISD::UMAX,       MVT::v16i32,  1 },
2707     { ISD::UMAX,       MVT::v32i16,  2 }, // FIXME: include split
2708     { ISD::UMAX,       MVT::v64i8,   2 }, // FIXME: include split
2709     { ISD::UMAX,       MVT::v4i64,   1 },
2710     { ISD::UMAX,       MVT::v2i64,   1 },
2711     { ISD::UMIN,       MVT::v8i64,   1 },
2712     { ISD::UMIN,       MVT::v16i32,  1 },
2713     { ISD::UMIN,       MVT::v32i16,  2 }, // FIXME: include split
2714     { ISD::UMIN,       MVT::v64i8,   2 }, // FIXME: include split
2715     { ISD::UMIN,       MVT::v4i64,   1 },
2716     { ISD::UMIN,       MVT::v2i64,   1 },
2717     { ISD::USUBSAT,    MVT::v16i32,  2 }, // pmaxud + psubd
2718     { ISD::USUBSAT,    MVT::v2i64,   2 }, // pmaxuq + psubq
2719     { ISD::USUBSAT,    MVT::v4i64,   2 }, // pmaxuq + psubq
2720     { ISD::USUBSAT,    MVT::v8i64,   2 }, // pmaxuq + psubq
2721     { ISD::UADDSAT,    MVT::v16i32,  3 }, // not + pminud + paddd
2722     { ISD::UADDSAT,    MVT::v2i64,   3 }, // not + pminuq + paddq
2723     { ISD::UADDSAT,    MVT::v4i64,   3 }, // not + pminuq + paddq
2724     { ISD::UADDSAT,    MVT::v8i64,   3 }, // not + pminuq + paddq
2725     { ISD::SADDSAT,    MVT::v32i16,  2 }, // FIXME: include split
2726     { ISD::SADDSAT,    MVT::v64i8,   2 }, // FIXME: include split
2727     { ISD::SSUBSAT,    MVT::v32i16,  2 }, // FIXME: include split
2728     { ISD::SSUBSAT,    MVT::v64i8,   2 }, // FIXME: include split
2729     { ISD::UADDSAT,    MVT::v32i16,  2 }, // FIXME: include split
2730     { ISD::UADDSAT,    MVT::v64i8,   2 }, // FIXME: include split
2731     { ISD::USUBSAT,    MVT::v32i16,  2 }, // FIXME: include split
2732     { ISD::USUBSAT,    MVT::v64i8,   2 }, // FIXME: include split
2733     { ISD::FMAXNUM,    MVT::f32,     2 },
2734     { ISD::FMAXNUM,    MVT::v4f32,   2 },
2735     { ISD::FMAXNUM,    MVT::v8f32,   2 },
2736     { ISD::FMAXNUM,    MVT::v16f32,  2 },
2737     { ISD::FMAXNUM,    MVT::f64,     2 },
2738     { ISD::FMAXNUM,    MVT::v2f64,   2 },
2739     { ISD::FMAXNUM,    MVT::v4f64,   2 },
2740     { ISD::FMAXNUM,    MVT::v8f64,   2 },
2741   };
2742   static const CostTblEntry XOPCostTbl[] = {
2743     { ISD::BITREVERSE, MVT::v4i64,   4 },
2744     { ISD::BITREVERSE, MVT::v8i32,   4 },
2745     { ISD::BITREVERSE, MVT::v16i16,  4 },
2746     { ISD::BITREVERSE, MVT::v32i8,   4 },
2747     { ISD::BITREVERSE, MVT::v2i64,   1 },
2748     { ISD::BITREVERSE, MVT::v4i32,   1 },
2749     { ISD::BITREVERSE, MVT::v8i16,   1 },
2750     { ISD::BITREVERSE, MVT::v16i8,   1 },
2751     { ISD::BITREVERSE, MVT::i64,     3 },
2752     { ISD::BITREVERSE, MVT::i32,     3 },
2753     { ISD::BITREVERSE, MVT::i16,     3 },
2754     { ISD::BITREVERSE, MVT::i8,      3 }
2755   };
2756   static const CostTblEntry AVX2CostTbl[] = {
2757     { ISD::ABS,        MVT::v4i64,   2 }, // VBLENDVPD(X,VPSUBQ(0,X),X)
2758     { ISD::ABS,        MVT::v8i32,   1 },
2759     { ISD::ABS,        MVT::v16i16,  1 },
2760     { ISD::ABS,        MVT::v32i8,   1 },
2761     { ISD::BITREVERSE, MVT::v4i64,   5 },
2762     { ISD::BITREVERSE, MVT::v8i32,   5 },
2763     { ISD::BITREVERSE, MVT::v16i16,  5 },
2764     { ISD::BITREVERSE, MVT::v32i8,   5 },
2765     { ISD::BSWAP,      MVT::v4i64,   1 },
2766     { ISD::BSWAP,      MVT::v8i32,   1 },
2767     { ISD::BSWAP,      MVT::v16i16,  1 },
2768     { ISD::CTLZ,       MVT::v4i64,  23 },
2769     { ISD::CTLZ,       MVT::v8i32,  18 },
2770     { ISD::CTLZ,       MVT::v16i16, 14 },
2771     { ISD::CTLZ,       MVT::v32i8,   9 },
2772     { ISD::CTPOP,      MVT::v4i64,   7 },
2773     { ISD::CTPOP,      MVT::v8i32,  11 },
2774     { ISD::CTPOP,      MVT::v16i16,  9 },
2775     { ISD::CTPOP,      MVT::v32i8,   6 },
2776     { ISD::CTTZ,       MVT::v4i64,  10 },
2777     { ISD::CTTZ,       MVT::v8i32,  14 },
2778     { ISD::CTTZ,       MVT::v16i16, 12 },
2779     { ISD::CTTZ,       MVT::v32i8,   9 },
2780     { ISD::SADDSAT,    MVT::v16i16,  1 },
2781     { ISD::SADDSAT,    MVT::v32i8,   1 },
2782     { ISD::SMAX,       MVT::v8i32,   1 },
2783     { ISD::SMAX,       MVT::v16i16,  1 },
2784     { ISD::SMAX,       MVT::v32i8,   1 },
2785     { ISD::SMIN,       MVT::v8i32,   1 },
2786     { ISD::SMIN,       MVT::v16i16,  1 },
2787     { ISD::SMIN,       MVT::v32i8,   1 },
2788     { ISD::SSUBSAT,    MVT::v16i16,  1 },
2789     { ISD::SSUBSAT,    MVT::v32i8,   1 },
2790     { ISD::UADDSAT,    MVT::v16i16,  1 },
2791     { ISD::UADDSAT,    MVT::v32i8,   1 },
2792     { ISD::UADDSAT,    MVT::v8i32,   3 }, // not + pminud + paddd
2793     { ISD::UMAX,       MVT::v8i32,   1 },
2794     { ISD::UMAX,       MVT::v16i16,  1 },
2795     { ISD::UMAX,       MVT::v32i8,   1 },
2796     { ISD::UMIN,       MVT::v8i32,   1 },
2797     { ISD::UMIN,       MVT::v16i16,  1 },
2798     { ISD::UMIN,       MVT::v32i8,   1 },
2799     { ISD::USUBSAT,    MVT::v16i16,  1 },
2800     { ISD::USUBSAT,    MVT::v32i8,   1 },
2801     { ISD::USUBSAT,    MVT::v8i32,   2 }, // pmaxud + psubd
2802     { ISD::FMAXNUM,    MVT::v8f32,   3 }, // MAXPS + CMPUNORDPS + BLENDVPS
2803     { ISD::FMAXNUM,    MVT::v4f64,   3 }, // MAXPD + CMPUNORDPD + BLENDVPD
2804     { ISD::FSQRT,      MVT::f32,     7 }, // Haswell from http://www.agner.org/
2805     { ISD::FSQRT,      MVT::v4f32,   7 }, // Haswell from http://www.agner.org/
2806     { ISD::FSQRT,      MVT::v8f32,  14 }, // Haswell from http://www.agner.org/
2807     { ISD::FSQRT,      MVT::f64,    14 }, // Haswell from http://www.agner.org/
2808     { ISD::FSQRT,      MVT::v2f64,  14 }, // Haswell from http://www.agner.org/
2809     { ISD::FSQRT,      MVT::v4f64,  28 }, // Haswell from http://www.agner.org/
2810   };
2811   static const CostTblEntry AVX1CostTbl[] = {
2812     { ISD::ABS,        MVT::v4i64,   5 }, // VBLENDVPD(X,VPSUBQ(0,X),X)
2813     { ISD::ABS,        MVT::v8i32,   3 },
2814     { ISD::ABS,        MVT::v16i16,  3 },
2815     { ISD::ABS,        MVT::v32i8,   3 },
2816     { ISD::BITREVERSE, MVT::v4i64,  12 }, // 2 x 128-bit Op + extract/insert
2817     { ISD::BITREVERSE, MVT::v8i32,  12 }, // 2 x 128-bit Op + extract/insert
2818     { ISD::BITREVERSE, MVT::v16i16, 12 }, // 2 x 128-bit Op + extract/insert
2819     { ISD::BITREVERSE, MVT::v32i8,  12 }, // 2 x 128-bit Op + extract/insert
2820     { ISD::BSWAP,      MVT::v4i64,   4 },
2821     { ISD::BSWAP,      MVT::v8i32,   4 },
2822     { ISD::BSWAP,      MVT::v16i16,  4 },
2823     { ISD::CTLZ,       MVT::v4i64,  48 }, // 2 x 128-bit Op + extract/insert
2824     { ISD::CTLZ,       MVT::v8i32,  38 }, // 2 x 128-bit Op + extract/insert
2825     { ISD::CTLZ,       MVT::v16i16, 30 }, // 2 x 128-bit Op + extract/insert
2826     { ISD::CTLZ,       MVT::v32i8,  20 }, // 2 x 128-bit Op + extract/insert
2827     { ISD::CTPOP,      MVT::v4i64,  16 }, // 2 x 128-bit Op + extract/insert
2828     { ISD::CTPOP,      MVT::v8i32,  24 }, // 2 x 128-bit Op + extract/insert
2829     { ISD::CTPOP,      MVT::v16i16, 20 }, // 2 x 128-bit Op + extract/insert
2830     { ISD::CTPOP,      MVT::v32i8,  14 }, // 2 x 128-bit Op + extract/insert
2831     { ISD::CTTZ,       MVT::v4i64,  22 }, // 2 x 128-bit Op + extract/insert
2832     { ISD::CTTZ,       MVT::v8i32,  30 }, // 2 x 128-bit Op + extract/insert
2833     { ISD::CTTZ,       MVT::v16i16, 26 }, // 2 x 128-bit Op + extract/insert
2834     { ISD::CTTZ,       MVT::v32i8,  20 }, // 2 x 128-bit Op + extract/insert
2835     { ISD::SADDSAT,    MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2836     { ISD::SADDSAT,    MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2837     { ISD::SMAX,       MVT::v8i32,   4 }, // 2 x 128-bit Op + extract/insert
2838     { ISD::SMAX,       MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2839     { ISD::SMAX,       MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2840     { ISD::SMIN,       MVT::v8i32,   4 }, // 2 x 128-bit Op + extract/insert
2841     { ISD::SMIN,       MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2842     { ISD::SMIN,       MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2843     { ISD::SSUBSAT,    MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2844     { ISD::SSUBSAT,    MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2845     { ISD::UADDSAT,    MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2846     { ISD::UADDSAT,    MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2847     { ISD::UADDSAT,    MVT::v8i32,   8 }, // 2 x 128-bit Op + extract/insert
2848     { ISD::UMAX,       MVT::v8i32,   4 }, // 2 x 128-bit Op + extract/insert
2849     { ISD::UMAX,       MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2850     { ISD::UMAX,       MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2851     { ISD::UMIN,       MVT::v8i32,   4 }, // 2 x 128-bit Op + extract/insert
2852     { ISD::UMIN,       MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2853     { ISD::UMIN,       MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2854     { ISD::USUBSAT,    MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2855     { ISD::USUBSAT,    MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2856     { ISD::USUBSAT,    MVT::v8i32,   6 }, // 2 x 128-bit Op + extract/insert
2857     { ISD::FMAXNUM,    MVT::f32,     3 }, // MAXSS + CMPUNORDSS + BLENDVPS
2858     { ISD::FMAXNUM,    MVT::v4f32,   3 }, // MAXPS + CMPUNORDPS + BLENDVPS
2859     { ISD::FMAXNUM,    MVT::v8f32,   5 }, // MAXPS + CMPUNORDPS + BLENDVPS + ?
2860     { ISD::FMAXNUM,    MVT::f64,     3 }, // MAXSD + CMPUNORDSD + BLENDVPD
2861     { ISD::FMAXNUM,    MVT::v2f64,   3 }, // MAXPD + CMPUNORDPD + BLENDVPD
2862     { ISD::FMAXNUM,    MVT::v4f64,   5 }, // MAXPD + CMPUNORDPD + BLENDVPD + ?
2863     { ISD::FSQRT,      MVT::f32,    14 }, // SNB from http://www.agner.org/
2864     { ISD::FSQRT,      MVT::v4f32,  14 }, // SNB from http://www.agner.org/
2865     { ISD::FSQRT,      MVT::v8f32,  28 }, // SNB from http://www.agner.org/
2866     { ISD::FSQRT,      MVT::f64,    21 }, // SNB from http://www.agner.org/
2867     { ISD::FSQRT,      MVT::v2f64,  21 }, // SNB from http://www.agner.org/
2868     { ISD::FSQRT,      MVT::v4f64,  43 }, // SNB from http://www.agner.org/
2869   };
2870   static const CostTblEntry GLMCostTbl[] = {
2871     { ISD::FSQRT, MVT::f32,   19 }, // sqrtss
2872     { ISD::FSQRT, MVT::v4f32, 37 }, // sqrtps
2873     { ISD::FSQRT, MVT::f64,   34 }, // sqrtsd
2874     { ISD::FSQRT, MVT::v2f64, 67 }, // sqrtpd
2875   };
2876   static const CostTblEntry SLMCostTbl[] = {
2877     { ISD::FSQRT, MVT::f32,   20 }, // sqrtss
2878     { ISD::FSQRT, MVT::v4f32, 40 }, // sqrtps
2879     { ISD::FSQRT, MVT::f64,   35 }, // sqrtsd
2880     { ISD::FSQRT, MVT::v2f64, 70 }, // sqrtpd
2881   };
2882   static const CostTblEntry SSE42CostTbl[] = {
2883     { ISD::USUBSAT,    MVT::v4i32,   2 }, // pmaxud + psubd
2884     { ISD::UADDSAT,    MVT::v4i32,   3 }, // not + pminud + paddd
2885     { ISD::FSQRT,      MVT::f32,    18 }, // Nehalem from http://www.agner.org/
2886     { ISD::FSQRT,      MVT::v4f32,  18 }, // Nehalem from http://www.agner.org/
2887   };
2888   static const CostTblEntry SSE41CostTbl[] = {
2889     { ISD::ABS,        MVT::v2i64,   2 }, // BLENDVPD(X,PSUBQ(0,X),X)
2890     { ISD::SMAX,       MVT::v4i32,   1 },
2891     { ISD::SMAX,       MVT::v16i8,   1 },
2892     { ISD::SMIN,       MVT::v4i32,   1 },
2893     { ISD::SMIN,       MVT::v16i8,   1 },
2894     { ISD::UMAX,       MVT::v4i32,   1 },
2895     { ISD::UMAX,       MVT::v8i16,   1 },
2896     { ISD::UMIN,       MVT::v4i32,   1 },
2897     { ISD::UMIN,       MVT::v8i16,   1 },
2898   };
2899   static const CostTblEntry SSSE3CostTbl[] = {
2900     { ISD::ABS,        MVT::v4i32,   1 },
2901     { ISD::ABS,        MVT::v8i16,   1 },
2902     { ISD::ABS,        MVT::v16i8,   1 },
2903     { ISD::BITREVERSE, MVT::v2i64,   5 },
2904     { ISD::BITREVERSE, MVT::v4i32,   5 },
2905     { ISD::BITREVERSE, MVT::v8i16,   5 },
2906     { ISD::BITREVERSE, MVT::v16i8,   5 },
2907     { ISD::BSWAP,      MVT::v2i64,   1 },
2908     { ISD::BSWAP,      MVT::v4i32,   1 },
2909     { ISD::BSWAP,      MVT::v8i16,   1 },
2910     { ISD::CTLZ,       MVT::v2i64,  23 },
2911     { ISD::CTLZ,       MVT::v4i32,  18 },
2912     { ISD::CTLZ,       MVT::v8i16,  14 },
2913     { ISD::CTLZ,       MVT::v16i8,   9 },
2914     { ISD::CTPOP,      MVT::v2i64,   7 },
2915     { ISD::CTPOP,      MVT::v4i32,  11 },
2916     { ISD::CTPOP,      MVT::v8i16,   9 },
2917     { ISD::CTPOP,      MVT::v16i8,   6 },
2918     { ISD::CTTZ,       MVT::v2i64,  10 },
2919     { ISD::CTTZ,       MVT::v4i32,  14 },
2920     { ISD::CTTZ,       MVT::v8i16,  12 },
2921     { ISD::CTTZ,       MVT::v16i8,   9 }
2922   };
2923   static const CostTblEntry SSE2CostTbl[] = {
2924     { ISD::ABS,        MVT::v2i64,   4 },
2925     { ISD::ABS,        MVT::v4i32,   3 },
2926     { ISD::ABS,        MVT::v8i16,   2 },
2927     { ISD::ABS,        MVT::v16i8,   2 },
2928     { ISD::BITREVERSE, MVT::v2i64,  29 },
2929     { ISD::BITREVERSE, MVT::v4i32,  27 },
2930     { ISD::BITREVERSE, MVT::v8i16,  27 },
2931     { ISD::BITREVERSE, MVT::v16i8,  20 },
2932     { ISD::BSWAP,      MVT::v2i64,   7 },
2933     { ISD::BSWAP,      MVT::v4i32,   7 },
2934     { ISD::BSWAP,      MVT::v8i16,   7 },
2935     { ISD::CTLZ,       MVT::v2i64,  25 },
2936     { ISD::CTLZ,       MVT::v4i32,  26 },
2937     { ISD::CTLZ,       MVT::v8i16,  20 },
2938     { ISD::CTLZ,       MVT::v16i8,  17 },
2939     { ISD::CTPOP,      MVT::v2i64,  12 },
2940     { ISD::CTPOP,      MVT::v4i32,  15 },
2941     { ISD::CTPOP,      MVT::v8i16,  13 },
2942     { ISD::CTPOP,      MVT::v16i8,  10 },
2943     { ISD::CTTZ,       MVT::v2i64,  14 },
2944     { ISD::CTTZ,       MVT::v4i32,  18 },
2945     { ISD::CTTZ,       MVT::v8i16,  16 },
2946     { ISD::CTTZ,       MVT::v16i8,  13 },
2947     { ISD::SADDSAT,    MVT::v8i16,   1 },
2948     { ISD::SADDSAT,    MVT::v16i8,   1 },
2949     { ISD::SMAX,       MVT::v8i16,   1 },
2950     { ISD::SMIN,       MVT::v8i16,   1 },
2951     { ISD::SSUBSAT,    MVT::v8i16,   1 },
2952     { ISD::SSUBSAT,    MVT::v16i8,   1 },
2953     { ISD::UADDSAT,    MVT::v8i16,   1 },
2954     { ISD::UADDSAT,    MVT::v16i8,   1 },
2955     { ISD::UMAX,       MVT::v8i16,   2 },
2956     { ISD::UMAX,       MVT::v16i8,   1 },
2957     { ISD::UMIN,       MVT::v8i16,   2 },
2958     { ISD::UMIN,       MVT::v16i8,   1 },
2959     { ISD::USUBSAT,    MVT::v8i16,   1 },
2960     { ISD::USUBSAT,    MVT::v16i8,   1 },
2961     { ISD::FMAXNUM,    MVT::f64,     4 },
2962     { ISD::FMAXNUM,    MVT::v2f64,   4 },
2963     { ISD::FSQRT,      MVT::f64,    32 }, // Nehalem from http://www.agner.org/
2964     { ISD::FSQRT,      MVT::v2f64,  32 }, // Nehalem from http://www.agner.org/
2965   };
2966   static const CostTblEntry SSE1CostTbl[] = {
2967     { ISD::FMAXNUM,    MVT::f32,     4 },
2968     { ISD::FMAXNUM,    MVT::v4f32,   4 },
2969     { ISD::FSQRT,      MVT::f32,    28 }, // Pentium III from http://www.agner.org/
2970     { ISD::FSQRT,      MVT::v4f32,  56 }, // Pentium III from http://www.agner.org/
2971   };
2972   static const CostTblEntry BMI64CostTbl[] = { // 64-bit targets
2973     { ISD::CTTZ,       MVT::i64,     1 },
2974   };
2975   static const CostTblEntry BMI32CostTbl[] = { // 32 or 64-bit targets
2976     { ISD::CTTZ,       MVT::i32,     1 },
2977     { ISD::CTTZ,       MVT::i16,     1 },
2978     { ISD::CTTZ,       MVT::i8,      1 },
2979   };
2980   static const CostTblEntry LZCNT64CostTbl[] = { // 64-bit targets
2981     { ISD::CTLZ,       MVT::i64,     1 },
2982   };
2983   static const CostTblEntry LZCNT32CostTbl[] = { // 32 or 64-bit targets
2984     { ISD::CTLZ,       MVT::i32,     1 },
2985     { ISD::CTLZ,       MVT::i16,     1 },
2986     { ISD::CTLZ,       MVT::i8,      1 },
2987   };
2988   static const CostTblEntry POPCNT64CostTbl[] = { // 64-bit targets
2989     { ISD::CTPOP,      MVT::i64,     1 },
2990   };
2991   static const CostTblEntry POPCNT32CostTbl[] = { // 32 or 64-bit targets
2992     { ISD::CTPOP,      MVT::i32,     1 },
2993     { ISD::CTPOP,      MVT::i16,     1 },
2994     { ISD::CTPOP,      MVT::i8,      1 },
2995   };
2996   static const CostTblEntry X64CostTbl[] = { // 64-bit targets
2997     { ISD::ABS,        MVT::i64,     2 }, // SUB+CMOV
2998     { ISD::BITREVERSE, MVT::i64,    14 },
2999     { ISD::BSWAP,      MVT::i64,     1 },
3000     { ISD::CTLZ,       MVT::i64,     4 }, // BSR+XOR or BSR+XOR+CMOV
3001     { ISD::CTTZ,       MVT::i64,     3 }, // TEST+BSF+CMOV/BRANCH
3002     { ISD::CTPOP,      MVT::i64,    10 },
3003     { ISD::SADDO,      MVT::i64,     1 },
3004     { ISD::UADDO,      MVT::i64,     1 },
3005     { ISD::UMULO,      MVT::i64,     2 }, // mulq + seto
3006   };
3007   static const CostTblEntry X86CostTbl[] = { // 32 or 64-bit targets
3008     { ISD::ABS,        MVT::i32,     2 }, // SUB+CMOV
3009     { ISD::ABS,        MVT::i16,     2 }, // SUB+CMOV
3010     { ISD::BITREVERSE, MVT::i32,    14 },
3011     { ISD::BITREVERSE, MVT::i16,    14 },
3012     { ISD::BITREVERSE, MVT::i8,     11 },
3013     { ISD::BSWAP,      MVT::i32,     1 },
3014     { ISD::BSWAP,      MVT::i16,     1 }, // ROL
3015     { ISD::CTLZ,       MVT::i32,     4 }, // BSR+XOR or BSR+XOR+CMOV
3016     { ISD::CTLZ,       MVT::i16,     4 }, // BSR+XOR or BSR+XOR+CMOV
3017     { ISD::CTLZ,       MVT::i8,      4 }, // BSR+XOR or BSR+XOR+CMOV
3018     { ISD::CTTZ,       MVT::i32,     3 }, // TEST+BSF+CMOV/BRANCH
3019     { ISD::CTTZ,       MVT::i16,     3 }, // TEST+BSF+CMOV/BRANCH
3020     { ISD::CTTZ,       MVT::i8,      3 }, // TEST+BSF+CMOV/BRANCH
3021     { ISD::CTPOP,      MVT::i32,     8 },
3022     { ISD::CTPOP,      MVT::i16,     9 },
3023     { ISD::CTPOP,      MVT::i8,      7 },
3024     { ISD::SADDO,      MVT::i32,     1 },
3025     { ISD::SADDO,      MVT::i16,     1 },
3026     { ISD::SADDO,      MVT::i8,      1 },
3027     { ISD::UADDO,      MVT::i32,     1 },
3028     { ISD::UADDO,      MVT::i16,     1 },
3029     { ISD::UADDO,      MVT::i8,      1 },
3030     { ISD::UMULO,      MVT::i32,     2 }, // mul + seto
3031     { ISD::UMULO,      MVT::i16,     2 },
3032     { ISD::UMULO,      MVT::i8,      2 },
3033   };
3034 
3035   Type *RetTy = ICA.getReturnType();
3036   Type *OpTy = RetTy;
3037   Intrinsic::ID IID = ICA.getID();
3038   unsigned ISD = ISD::DELETED_NODE;
3039   switch (IID) {
3040   default:
3041     break;
3042   case Intrinsic::abs:
3043     ISD = ISD::ABS;
3044     break;
3045   case Intrinsic::bitreverse:
3046     ISD = ISD::BITREVERSE;
3047     break;
3048   case Intrinsic::bswap:
3049     ISD = ISD::BSWAP;
3050     break;
3051   case Intrinsic::ctlz:
3052     ISD = ISD::CTLZ;
3053     break;
3054   case Intrinsic::ctpop:
3055     ISD = ISD::CTPOP;
3056     break;
3057   case Intrinsic::cttz:
3058     ISD = ISD::CTTZ;
3059     break;
3060   case Intrinsic::maxnum:
3061   case Intrinsic::minnum:
3062     // FMINNUM has same costs so don't duplicate.
3063     ISD = ISD::FMAXNUM;
3064     break;
3065   case Intrinsic::sadd_sat:
3066     ISD = ISD::SADDSAT;
3067     break;
3068   case Intrinsic::smax:
3069     ISD = ISD::SMAX;
3070     break;
3071   case Intrinsic::smin:
3072     ISD = ISD::SMIN;
3073     break;
3074   case Intrinsic::ssub_sat:
3075     ISD = ISD::SSUBSAT;
3076     break;
3077   case Intrinsic::uadd_sat:
3078     ISD = ISD::UADDSAT;
3079     break;
3080   case Intrinsic::umax:
3081     ISD = ISD::UMAX;
3082     break;
3083   case Intrinsic::umin:
3084     ISD = ISD::UMIN;
3085     break;
3086   case Intrinsic::usub_sat:
3087     ISD = ISD::USUBSAT;
3088     break;
3089   case Intrinsic::sqrt:
3090     ISD = ISD::FSQRT;
3091     break;
3092   case Intrinsic::sadd_with_overflow:
3093   case Intrinsic::ssub_with_overflow:
3094     // SSUBO has same costs so don't duplicate.
3095     ISD = ISD::SADDO;
3096     OpTy = RetTy->getContainedType(0);
3097     break;
3098   case Intrinsic::uadd_with_overflow:
3099   case Intrinsic::usub_with_overflow:
3100     // USUBO has same costs so don't duplicate.
3101     ISD = ISD::UADDO;
3102     OpTy = RetTy->getContainedType(0);
3103     break;
3104   case Intrinsic::umul_with_overflow:
3105   case Intrinsic::smul_with_overflow:
3106     // SMULO has same costs so don't duplicate.
3107     ISD = ISD::UMULO;
3108     OpTy = RetTy->getContainedType(0);
3109     break;
3110   }
3111 
3112   if (ISD != ISD::DELETED_NODE) {
3113     // Legalize the type.
3114     std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, OpTy);
3115     MVT MTy = LT.second;
3116 
3117     // Attempt to lookup cost.
3118     if (ISD == ISD::BITREVERSE && ST->hasGFNI() && ST->hasSSSE3() &&
3119         MTy.isVector()) {
3120       // With PSHUFB the code is very similar for all types. If we have integer
3121       // byte operations, we just need a GF2P8AFFINEQB for vXi8. For other types
3122       // we also need a PSHUFB.
3123       unsigned Cost = MTy.getVectorElementType() == MVT::i8 ? 1 : 2;
3124 
3125       // Without byte operations, we need twice as many GF2P8AFFINEQB and PSHUFB
3126       // instructions. We also need an extract and an insert.
3127       if (!(MTy.is128BitVector() || (ST->hasAVX2() && MTy.is256BitVector()) ||
3128             (ST->hasBWI() && MTy.is512BitVector())))
3129         Cost = Cost * 2 + 2;
3130 
3131       return LT.first * Cost;
3132     }
3133 
3134     auto adjustTableCost = [](const CostTblEntry &Entry,
3135                               InstructionCost LegalizationCost,
3136                               FastMathFlags FMF) {
3137       // If there are no NANs to deal with, then these are reduced to a
3138       // single MIN** or MAX** instruction instead of the MIN/CMP/SELECT that we
3139       // assume is used in the non-fast case.
3140       if (Entry.ISD == ISD::FMAXNUM || Entry.ISD == ISD::FMINNUM) {
3141         if (FMF.noNaNs())
3142           return LegalizationCost * 1;
3143       }
3144       return LegalizationCost * (int)Entry.Cost;
3145     };
3146 
3147     if (ST->useGLMDivSqrtCosts())
3148       if (const auto *Entry = CostTableLookup(GLMCostTbl, ISD, MTy))
3149         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3150 
3151     if (ST->isSLM())
3152       if (const auto *Entry = CostTableLookup(SLMCostTbl, ISD, MTy))
3153         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3154 
3155     if (ST->hasBITALG())
3156       if (const auto *Entry = CostTableLookup(AVX512BITALGCostTbl, ISD, MTy))
3157         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3158 
3159     if (ST->hasVPOPCNTDQ())
3160       if (const auto *Entry = CostTableLookup(AVX512VPOPCNTDQCostTbl, ISD, MTy))
3161         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3162 
3163     if (ST->hasCDI())
3164       if (const auto *Entry = CostTableLookup(AVX512CDCostTbl, ISD, MTy))
3165         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3166 
3167     if (ST->hasBWI())
3168       if (const auto *Entry = CostTableLookup(AVX512BWCostTbl, ISD, MTy))
3169         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3170 
3171     if (ST->hasAVX512())
3172       if (const auto *Entry = CostTableLookup(AVX512CostTbl, ISD, MTy))
3173         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3174 
3175     if (ST->hasXOP())
3176       if (const auto *Entry = CostTableLookup(XOPCostTbl, ISD, MTy))
3177         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3178 
3179     if (ST->hasAVX2())
3180       if (const auto *Entry = CostTableLookup(AVX2CostTbl, ISD, MTy))
3181         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3182 
3183     if (ST->hasAVX())
3184       if (const auto *Entry = CostTableLookup(AVX1CostTbl, ISD, MTy))
3185         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3186 
3187     if (ST->hasSSE42())
3188       if (const auto *Entry = CostTableLookup(SSE42CostTbl, ISD, MTy))
3189         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3190 
3191     if (ST->hasSSE41())
3192       if (const auto *Entry = CostTableLookup(SSE41CostTbl, ISD, MTy))
3193         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3194 
3195     if (ST->hasSSSE3())
3196       if (const auto *Entry = CostTableLookup(SSSE3CostTbl, ISD, MTy))
3197         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3198 
3199     if (ST->hasSSE2())
3200       if (const auto *Entry = CostTableLookup(SSE2CostTbl, ISD, MTy))
3201         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3202 
3203     if (ST->hasSSE1())
3204       if (const auto *Entry = CostTableLookup(SSE1CostTbl, ISD, MTy))
3205         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3206 
3207     if (ST->hasBMI()) {
3208       if (ST->is64Bit())
3209         if (const auto *Entry = CostTableLookup(BMI64CostTbl, ISD, MTy))
3210           return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3211 
3212       if (const auto *Entry = CostTableLookup(BMI32CostTbl, ISD, MTy))
3213         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3214     }
3215 
3216     if (ST->hasLZCNT()) {
3217       if (ST->is64Bit())
3218         if (const auto *Entry = CostTableLookup(LZCNT64CostTbl, ISD, MTy))
3219           return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3220 
3221       if (const auto *Entry = CostTableLookup(LZCNT32CostTbl, ISD, MTy))
3222         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3223     }
3224 
3225     if (ST->hasPOPCNT()) {
3226       if (ST->is64Bit())
3227         if (const auto *Entry = CostTableLookup(POPCNT64CostTbl, ISD, MTy))
3228           return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3229 
3230       if (const auto *Entry = CostTableLookup(POPCNT32CostTbl, ISD, MTy))
3231         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3232     }
3233 
3234     if (ISD == ISD::BSWAP && ST->hasMOVBE() && ST->hasFastMOVBE()) {
3235       if (const Instruction *II = ICA.getInst()) {
3236         if (II->hasOneUse() && isa<StoreInst>(II->user_back()))
3237           return TTI::TCC_Free;
3238         if (auto *LI = dyn_cast<LoadInst>(II->getOperand(0))) {
3239           if (LI->hasOneUse())
3240             return TTI::TCC_Free;
3241         }
3242       }
3243     }
3244 
3245     // TODO - add BMI (TZCNT) scalar handling
3246 
3247     if (ST->is64Bit())
3248       if (const auto *Entry = CostTableLookup(X64CostTbl, ISD, MTy))
3249         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3250 
3251     if (const auto *Entry = CostTableLookup(X86CostTbl, ISD, MTy))
3252       return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3253   }
3254 
3255   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
3256 }
3257 
3258 InstructionCost
3259 X86TTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
3260                                   TTI::TargetCostKind CostKind) {
3261   if (ICA.isTypeBasedOnly())
3262     return getTypeBasedIntrinsicInstrCost(ICA, CostKind);
3263 
3264   static const CostTblEntry AVX512CostTbl[] = {
3265     { ISD::ROTL,       MVT::v8i64,   1 },
3266     { ISD::ROTL,       MVT::v4i64,   1 },
3267     { ISD::ROTL,       MVT::v2i64,   1 },
3268     { ISD::ROTL,       MVT::v16i32,  1 },
3269     { ISD::ROTL,       MVT::v8i32,   1 },
3270     { ISD::ROTL,       MVT::v4i32,   1 },
3271     { ISD::ROTR,       MVT::v8i64,   1 },
3272     { ISD::ROTR,       MVT::v4i64,   1 },
3273     { ISD::ROTR,       MVT::v2i64,   1 },
3274     { ISD::ROTR,       MVT::v16i32,  1 },
3275     { ISD::ROTR,       MVT::v8i32,   1 },
3276     { ISD::ROTR,       MVT::v4i32,   1 }
3277   };
3278   // XOP: ROTL = VPROT(X,Y), ROTR = VPROT(X,SUB(0,Y))
3279   static const CostTblEntry XOPCostTbl[] = {
3280     { ISD::ROTL,       MVT::v4i64,   4 },
3281     { ISD::ROTL,       MVT::v8i32,   4 },
3282     { ISD::ROTL,       MVT::v16i16,  4 },
3283     { ISD::ROTL,       MVT::v32i8,   4 },
3284     { ISD::ROTL,       MVT::v2i64,   1 },
3285     { ISD::ROTL,       MVT::v4i32,   1 },
3286     { ISD::ROTL,       MVT::v8i16,   1 },
3287     { ISD::ROTL,       MVT::v16i8,   1 },
3288     { ISD::ROTR,       MVT::v4i64,   6 },
3289     { ISD::ROTR,       MVT::v8i32,   6 },
3290     { ISD::ROTR,       MVT::v16i16,  6 },
3291     { ISD::ROTR,       MVT::v32i8,   6 },
3292     { ISD::ROTR,       MVT::v2i64,   2 },
3293     { ISD::ROTR,       MVT::v4i32,   2 },
3294     { ISD::ROTR,       MVT::v8i16,   2 },
3295     { ISD::ROTR,       MVT::v16i8,   2 }
3296   };
3297   static const CostTblEntry X64CostTbl[] = { // 64-bit targets
3298     { ISD::ROTL,       MVT::i64,     1 },
3299     { ISD::ROTR,       MVT::i64,     1 },
3300     { ISD::FSHL,       MVT::i64,     4 }
3301   };
3302   static const CostTblEntry X86CostTbl[] = { // 32 or 64-bit targets
3303     { ISD::ROTL,       MVT::i32,     1 },
3304     { ISD::ROTL,       MVT::i16,     1 },
3305     { ISD::ROTL,       MVT::i8,      1 },
3306     { ISD::ROTR,       MVT::i32,     1 },
3307     { ISD::ROTR,       MVT::i16,     1 },
3308     { ISD::ROTR,       MVT::i8,      1 },
3309     { ISD::FSHL,       MVT::i32,     4 },
3310     { ISD::FSHL,       MVT::i16,     4 },
3311     { ISD::FSHL,       MVT::i8,      4 }
3312   };
3313 
3314   Intrinsic::ID IID = ICA.getID();
3315   Type *RetTy = ICA.getReturnType();
3316   const SmallVectorImpl<const Value *> &Args = ICA.getArgs();
3317   unsigned ISD = ISD::DELETED_NODE;
3318   switch (IID) {
3319   default:
3320     break;
3321   case Intrinsic::fshl:
3322     ISD = ISD::FSHL;
3323     if (Args[0] == Args[1])
3324       ISD = ISD::ROTL;
3325     break;
3326   case Intrinsic::fshr:
3327     // FSHR has same costs so don't duplicate.
3328     ISD = ISD::FSHL;
3329     if (Args[0] == Args[1])
3330       ISD = ISD::ROTR;
3331     break;
3332   }
3333 
3334   if (ISD != ISD::DELETED_NODE) {
3335     // Legalize the type.
3336     std::pair<InstructionCost, MVT> LT =
3337         TLI->getTypeLegalizationCost(DL, RetTy);
3338     MVT MTy = LT.second;
3339 
3340     // Attempt to lookup cost.
3341     if (ST->hasAVX512())
3342       if (const auto *Entry = CostTableLookup(AVX512CostTbl, ISD, MTy))
3343         return LT.first * Entry->Cost;
3344 
3345     if (ST->hasXOP())
3346       if (const auto *Entry = CostTableLookup(XOPCostTbl, ISD, MTy))
3347         return LT.first * Entry->Cost;
3348 
3349     if (ST->is64Bit())
3350       if (const auto *Entry = CostTableLookup(X64CostTbl, ISD, MTy))
3351         return LT.first * Entry->Cost;
3352 
3353     if (const auto *Entry = CostTableLookup(X86CostTbl, ISD, MTy))
3354       return LT.first * Entry->Cost;
3355   }
3356 
3357   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
3358 }
3359 
3360 InstructionCost X86TTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val,
3361                                                unsigned Index) {
3362   static const CostTblEntry SLMCostTbl[] = {
3363      { ISD::EXTRACT_VECTOR_ELT,       MVT::i8,      4 },
3364      { ISD::EXTRACT_VECTOR_ELT,       MVT::i16,     4 },
3365      { ISD::EXTRACT_VECTOR_ELT,       MVT::i32,     4 },
3366      { ISD::EXTRACT_VECTOR_ELT,       MVT::i64,     7 }
3367    };
3368 
3369   assert(Val->isVectorTy() && "This must be a vector type");
3370   Type *ScalarType = Val->getScalarType();
3371   int RegisterFileMoveCost = 0;
3372 
3373   // Non-immediate extraction/insertion can be handled as a sequence of
3374   // aliased loads+stores via the stack.
3375   if (Index == -1U && (Opcode == Instruction::ExtractElement ||
3376                        Opcode == Instruction::InsertElement)) {
3377     // TODO: On some SSE41+ targets, we expand to cmp+splat+select patterns:
3378     // inselt N0, N1, N2 --> select (SplatN2 == {0,1,2...}) ? SplatN1 : N0.
3379 
3380     // TODO: Move this to BasicTTIImpl.h? We'd need better gep + index handling.
3381     assert(isa<FixedVectorType>(Val) && "Fixed vector type expected");
3382     Align VecAlign = DL.getPrefTypeAlign(Val);
3383     Align SclAlign = DL.getPrefTypeAlign(ScalarType);
3384 
3385     // Extract - store vector to stack, load scalar.
3386     if (Opcode == Instruction::ExtractElement) {
3387       return getMemoryOpCost(Instruction::Store, Val, VecAlign, 0,
3388                              TTI::TargetCostKind::TCK_RecipThroughput) +
3389              getMemoryOpCost(Instruction::Load, ScalarType, SclAlign, 0,
3390                              TTI::TargetCostKind::TCK_RecipThroughput);
3391     }
3392     // Insert - store vector to stack, store scalar, load vector.
3393     if (Opcode == Instruction::InsertElement) {
3394       return getMemoryOpCost(Instruction::Store, Val, VecAlign, 0,
3395                              TTI::TargetCostKind::TCK_RecipThroughput) +
3396              getMemoryOpCost(Instruction::Store, ScalarType, SclAlign, 0,
3397                              TTI::TargetCostKind::TCK_RecipThroughput) +
3398              getMemoryOpCost(Instruction::Load, Val, VecAlign, 0,
3399                              TTI::TargetCostKind::TCK_RecipThroughput);
3400     }
3401   }
3402 
3403   if (Index != -1U && (Opcode == Instruction::ExtractElement ||
3404                        Opcode == Instruction::InsertElement)) {
3405     // Legalize the type.
3406     std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Val);
3407 
3408     // This type is legalized to a scalar type.
3409     if (!LT.second.isVector())
3410       return 0;
3411 
3412     // The type may be split. Normalize the index to the new type.
3413     unsigned NumElts = LT.second.getVectorNumElements();
3414     unsigned SubNumElts = NumElts;
3415     Index = Index % NumElts;
3416 
3417     // For >128-bit vectors, we need to extract higher 128-bit subvectors.
3418     // For inserts, we also need to insert the subvector back.
3419     if (LT.second.getSizeInBits() > 128) {
3420       assert((LT.second.getSizeInBits() % 128) == 0 && "Illegal vector");
3421       unsigned NumSubVecs = LT.second.getSizeInBits() / 128;
3422       SubNumElts = NumElts / NumSubVecs;
3423       if (SubNumElts <= Index) {
3424         RegisterFileMoveCost += (Opcode == Instruction::InsertElement ? 2 : 1);
3425         Index %= SubNumElts;
3426       }
3427     }
3428 
3429     if (Index == 0) {
3430       // Floating point scalars are already located in index #0.
3431       // Many insertions to #0 can fold away for scalar fp-ops, so let's assume
3432       // true for all.
3433       if (ScalarType->isFloatingPointTy())
3434         return RegisterFileMoveCost;
3435 
3436       // Assume movd/movq XMM -> GPR is relatively cheap on all targets.
3437       if (ScalarType->isIntegerTy() && Opcode == Instruction::ExtractElement)
3438         return 1 + RegisterFileMoveCost;
3439     }
3440 
3441     int ISD = TLI->InstructionOpcodeToISD(Opcode);
3442     assert(ISD && "Unexpected vector opcode");
3443     MVT MScalarTy = LT.second.getScalarType();
3444     if (ST->isSLM())
3445       if (auto *Entry = CostTableLookup(SLMCostTbl, ISD, MScalarTy))
3446         return Entry->Cost + RegisterFileMoveCost;
3447 
3448     // Assume pinsr/pextr XMM <-> GPR is relatively cheap on all targets.
3449     if ((MScalarTy == MVT::i16 && ST->hasSSE2()) ||
3450         (MScalarTy.isInteger() && ST->hasSSE41()))
3451       return 1 + RegisterFileMoveCost;
3452 
3453     // Assume insertps is relatively cheap on all targets.
3454     if (MScalarTy == MVT::f32 && ST->hasSSE41() &&
3455         Opcode == Instruction::InsertElement)
3456       return 1 + RegisterFileMoveCost;
3457 
3458     // For extractions we just need to shuffle the element to index 0, which
3459     // should be very cheap (assume cost = 1). For insertions we need to shuffle
3460     // the elements to its destination. In both cases we must handle the
3461     // subvector move(s).
3462     // If the vector type is already less than 128-bits then don't reduce it.
3463     // TODO: Under what circumstances should we shuffle using the full width?
3464     InstructionCost ShuffleCost = 1;
3465     if (Opcode == Instruction::InsertElement) {
3466       auto *SubTy = cast<VectorType>(Val);
3467       EVT VT = TLI->getValueType(DL, Val);
3468       if (VT.getScalarType() != MScalarTy || VT.getSizeInBits() >= 128)
3469         SubTy = FixedVectorType::get(ScalarType, SubNumElts);
3470       ShuffleCost =
3471           getShuffleCost(TTI::SK_PermuteTwoSrc, SubTy, None, 0, SubTy);
3472     }
3473     int IntOrFpCost = ScalarType->isFloatingPointTy() ? 0 : 1;
3474     return ShuffleCost + IntOrFpCost + RegisterFileMoveCost;
3475   }
3476 
3477   // Add to the base cost if we know that the extracted element of a vector is
3478   // destined to be moved to and used in the integer register file.
3479   if (Opcode == Instruction::ExtractElement && ScalarType->isPointerTy())
3480     RegisterFileMoveCost += 1;
3481 
3482   return BaseT::getVectorInstrCost(Opcode, Val, Index) + RegisterFileMoveCost;
3483 }
3484 
3485 InstructionCost X86TTIImpl::getScalarizationOverhead(VectorType *Ty,
3486                                                      const APInt &DemandedElts,
3487                                                      bool Insert,
3488                                                      bool Extract) {
3489   InstructionCost Cost = 0;
3490 
3491   // For insertions, a ISD::BUILD_VECTOR style vector initialization can be much
3492   // cheaper than an accumulation of ISD::INSERT_VECTOR_ELT.
3493   if (Insert) {
3494     std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
3495     MVT MScalarTy = LT.second.getScalarType();
3496 
3497     if ((MScalarTy == MVT::i16 && ST->hasSSE2()) ||
3498         (MScalarTy.isInteger() && ST->hasSSE41()) ||
3499         (MScalarTy == MVT::f32 && ST->hasSSE41())) {
3500       // For types we can insert directly, insertion into 128-bit sub vectors is
3501       // cheap, followed by a cheap chain of concatenations.
3502       if (LT.second.getSizeInBits() <= 128) {
3503         Cost +=
3504             BaseT::getScalarizationOverhead(Ty, DemandedElts, Insert, false);
3505       } else {
3506         // In each 128-lane, if at least one index is demanded but not all
3507         // indices are demanded and this 128-lane is not the first 128-lane of
3508         // the legalized-vector, then this 128-lane needs a extracti128; If in
3509         // each 128-lane, there is at least one demanded index, this 128-lane
3510         // needs a inserti128.
3511 
3512         // The following cases will help you build a better understanding:
3513         // Assume we insert several elements into a v8i32 vector in avx2,
3514         // Case#1: inserting into 1th index needs vpinsrd + inserti128.
3515         // Case#2: inserting into 5th index needs extracti128 + vpinsrd +
3516         // inserti128.
3517         // Case#3: inserting into 4,5,6,7 index needs 4*vpinsrd + inserti128.
3518         const int CostValue = *LT.first.getValue();
3519         assert(CostValue >= 0 && "Negative cost!");
3520         unsigned Num128Lanes = LT.second.getSizeInBits() / 128 * CostValue;
3521         unsigned NumElts = LT.second.getVectorNumElements() * CostValue;
3522         APInt WidenedDemandedElts = DemandedElts.zextOrSelf(NumElts);
3523         unsigned Scale = NumElts / Num128Lanes;
3524         // We iterate each 128-lane, and check if we need a
3525         // extracti128/inserti128 for this 128-lane.
3526         for (unsigned I = 0; I < NumElts; I += Scale) {
3527           APInt Mask = WidenedDemandedElts.getBitsSet(NumElts, I, I + Scale);
3528           APInt MaskedDE = Mask & WidenedDemandedElts;
3529           unsigned Population = MaskedDE.countPopulation();
3530           Cost += (Population > 0 && Population != Scale &&
3531                    I % LT.second.getVectorNumElements() != 0);
3532           Cost += Population > 0;
3533         }
3534         Cost += DemandedElts.countPopulation();
3535 
3536         // For vXf32 cases, insertion into the 0'th index in each v4f32
3537         // 128-bit vector is free.
3538         // NOTE: This assumes legalization widens vXf32 vectors.
3539         if (MScalarTy == MVT::f32)
3540           for (unsigned i = 0, e = cast<FixedVectorType>(Ty)->getNumElements();
3541                i < e; i += 4)
3542             if (DemandedElts[i])
3543               Cost--;
3544       }
3545     } else if (LT.second.isVector()) {
3546       // Without fast insertion, we need to use MOVD/MOVQ to pass each demanded
3547       // integer element as a SCALAR_TO_VECTOR, then we build the vector as a
3548       // series of UNPCK followed by CONCAT_VECTORS - all of these can be
3549       // considered cheap.
3550       if (Ty->isIntOrIntVectorTy())
3551         Cost += DemandedElts.countPopulation();
3552 
3553       // Get the smaller of the legalized or original pow2-extended number of
3554       // vector elements, which represents the number of unpacks we'll end up
3555       // performing.
3556       unsigned NumElts = LT.second.getVectorNumElements();
3557       unsigned Pow2Elts =
3558           PowerOf2Ceil(cast<FixedVectorType>(Ty)->getNumElements());
3559       Cost += (std::min<unsigned>(NumElts, Pow2Elts) - 1) * LT.first;
3560     }
3561   }
3562 
3563   // TODO: Use default extraction for now, but we should investigate extending this
3564   // to handle repeated subvector extraction.
3565   if (Extract)
3566     Cost += BaseT::getScalarizationOverhead(Ty, DemandedElts, false, Extract);
3567 
3568   return Cost;
3569 }
3570 
3571 InstructionCost X86TTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
3572                                             MaybeAlign Alignment,
3573                                             unsigned AddressSpace,
3574                                             TTI::TargetCostKind CostKind,
3575                                             const Instruction *I) {
3576   // TODO: Handle other cost kinds.
3577   if (CostKind != TTI::TCK_RecipThroughput) {
3578     if (auto *SI = dyn_cast_or_null<StoreInst>(I)) {
3579       // Store instruction with index and scale costs 2 Uops.
3580       // Check the preceding GEP to identify non-const indices.
3581       if (auto *GEP = dyn_cast<GetElementPtrInst>(SI->getPointerOperand())) {
3582         if (!all_of(GEP->indices(), [](Value *V) { return isa<Constant>(V); }))
3583           return TTI::TCC_Basic * 2;
3584       }
3585     }
3586     return TTI::TCC_Basic;
3587   }
3588 
3589   assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
3590          "Invalid Opcode");
3591   // Type legalization can't handle structs
3592   if (TLI->getValueType(DL, Src, true) == MVT::Other)
3593     return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
3594                                   CostKind);
3595 
3596   // Legalize the type.
3597   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
3598 
3599   auto *VTy = dyn_cast<FixedVectorType>(Src);
3600 
3601   // Handle the simple case of non-vectors.
3602   // NOTE: this assumes that legalization never creates vector from scalars!
3603   if (!VTy || !LT.second.isVector())
3604     // Each load/store unit costs 1.
3605     return LT.first * 1;
3606 
3607   bool IsLoad = Opcode == Instruction::Load;
3608 
3609   Type *EltTy = VTy->getElementType();
3610 
3611   const int EltTyBits = DL.getTypeSizeInBits(EltTy);
3612 
3613   InstructionCost Cost = 0;
3614 
3615   // Source of truth: how many elements were there in the original IR vector?
3616   const unsigned SrcNumElt = VTy->getNumElements();
3617 
3618   // How far have we gotten?
3619   int NumEltRemaining = SrcNumElt;
3620   // Note that we intentionally capture by-reference, NumEltRemaining changes.
3621   auto NumEltDone = [&]() { return SrcNumElt - NumEltRemaining; };
3622 
3623   const int MaxLegalOpSizeBytes = divideCeil(LT.second.getSizeInBits(), 8);
3624 
3625   // Note that even if we can store 64 bits of an XMM, we still operate on XMM.
3626   const unsigned XMMBits = 128;
3627   if (XMMBits % EltTyBits != 0)
3628     // Vector size must be a multiple of the element size. I.e. no padding.
3629     return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
3630                                   CostKind);
3631   const int NumEltPerXMM = XMMBits / EltTyBits;
3632 
3633   auto *XMMVecTy = FixedVectorType::get(EltTy, NumEltPerXMM);
3634 
3635   for (int CurrOpSizeBytes = MaxLegalOpSizeBytes, SubVecEltsLeft = 0;
3636        NumEltRemaining > 0; CurrOpSizeBytes /= 2) {
3637     // How many elements would a single op deal with at once?
3638     if ((8 * CurrOpSizeBytes) % EltTyBits != 0)
3639       // Vector size must be a multiple of the element size. I.e. no padding.
3640       return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
3641                                     CostKind);
3642     int CurrNumEltPerOp = (8 * CurrOpSizeBytes) / EltTyBits;
3643 
3644     assert(CurrOpSizeBytes > 0 && CurrNumEltPerOp > 0 && "How'd we get here?");
3645     assert((((NumEltRemaining * EltTyBits) < (2 * 8 * CurrOpSizeBytes)) ||
3646             (CurrOpSizeBytes == MaxLegalOpSizeBytes)) &&
3647            "Unless we haven't halved the op size yet, "
3648            "we have less than two op's sized units of work left.");
3649 
3650     auto *CurrVecTy = CurrNumEltPerOp > NumEltPerXMM
3651                           ? FixedVectorType::get(EltTy, CurrNumEltPerOp)
3652                           : XMMVecTy;
3653 
3654     assert(CurrVecTy->getNumElements() % CurrNumEltPerOp == 0 &&
3655            "After halving sizes, the vector elt count is no longer a multiple "
3656            "of number of elements per operation?");
3657     auto *CoalescedVecTy =
3658         CurrNumEltPerOp == 1
3659             ? CurrVecTy
3660             : FixedVectorType::get(
3661                   IntegerType::get(Src->getContext(),
3662                                    EltTyBits * CurrNumEltPerOp),
3663                   CurrVecTy->getNumElements() / CurrNumEltPerOp);
3664     assert(DL.getTypeSizeInBits(CoalescedVecTy) ==
3665                DL.getTypeSizeInBits(CurrVecTy) &&
3666            "coalesciing elements doesn't change vector width.");
3667 
3668     while (NumEltRemaining > 0) {
3669       assert(SubVecEltsLeft >= 0 && "Subreg element count overconsumtion?");
3670 
3671       // Can we use this vector size, as per the remaining element count?
3672       // Iff the vector is naturally aligned, we can do a wide load regardless.
3673       if (NumEltRemaining < CurrNumEltPerOp &&
3674           (!IsLoad || Alignment.valueOrOne() < CurrOpSizeBytes) &&
3675           CurrOpSizeBytes != 1)
3676         break; // Try smalled vector size.
3677 
3678       bool Is0thSubVec = (NumEltDone() % LT.second.getVectorNumElements()) == 0;
3679 
3680       // If we have fully processed the previous reg, we need to replenish it.
3681       if (SubVecEltsLeft == 0) {
3682         SubVecEltsLeft += CurrVecTy->getNumElements();
3683         // And that's free only for the 0'th subvector of a legalized vector.
3684         if (!Is0thSubVec)
3685           Cost += getShuffleCost(IsLoad ? TTI::ShuffleKind::SK_InsertSubvector
3686                                         : TTI::ShuffleKind::SK_ExtractSubvector,
3687                                  VTy, None, NumEltDone(), CurrVecTy);
3688       }
3689 
3690       // While we can directly load/store ZMM, YMM, and 64-bit halves of XMM,
3691       // for smaller widths (32/16/8) we have to insert/extract them separately.
3692       // Again, it's free for the 0'th subreg (if op is 32/64 bit wide,
3693       // but let's pretend that it is also true for 16/8 bit wide ops...)
3694       if (CurrOpSizeBytes <= 32 / 8 && !Is0thSubVec) {
3695         int NumEltDoneInCurrXMM = NumEltDone() % NumEltPerXMM;
3696         assert(NumEltDoneInCurrXMM % CurrNumEltPerOp == 0 && "");
3697         int CoalescedVecEltIdx = NumEltDoneInCurrXMM / CurrNumEltPerOp;
3698         APInt DemandedElts =
3699             APInt::getBitsSet(CoalescedVecTy->getNumElements(),
3700                               CoalescedVecEltIdx, CoalescedVecEltIdx + 1);
3701         assert(DemandedElts.countPopulation() == 1 && "Inserting single value");
3702         Cost += getScalarizationOverhead(CoalescedVecTy, DemandedElts, IsLoad,
3703                                          !IsLoad);
3704       }
3705 
3706       // This isn't exactly right. We're using slow unaligned 32-byte accesses
3707       // as a proxy for a double-pumped AVX memory interface such as on
3708       // Sandybridge.
3709       if (CurrOpSizeBytes == 32 && ST->isUnalignedMem32Slow())
3710         Cost += 2;
3711       else
3712         Cost += 1;
3713 
3714       SubVecEltsLeft -= CurrNumEltPerOp;
3715       NumEltRemaining -= CurrNumEltPerOp;
3716       Alignment = commonAlignment(Alignment.valueOrOne(), CurrOpSizeBytes);
3717     }
3718   }
3719 
3720   assert(NumEltRemaining <= 0 && "Should have processed all the elements.");
3721 
3722   return Cost;
3723 }
3724 
3725 InstructionCost
3726 X86TTIImpl::getMaskedMemoryOpCost(unsigned Opcode, Type *SrcTy, Align Alignment,
3727                                   unsigned AddressSpace,
3728                                   TTI::TargetCostKind CostKind) {
3729   bool IsLoad = (Instruction::Load == Opcode);
3730   bool IsStore = (Instruction::Store == Opcode);
3731 
3732   auto *SrcVTy = dyn_cast<FixedVectorType>(SrcTy);
3733   if (!SrcVTy)
3734     // To calculate scalar take the regular cost, without mask
3735     return getMemoryOpCost(Opcode, SrcTy, Alignment, AddressSpace, CostKind);
3736 
3737   unsigned NumElem = SrcVTy->getNumElements();
3738   auto *MaskTy =
3739       FixedVectorType::get(Type::getInt8Ty(SrcVTy->getContext()), NumElem);
3740   if ((IsLoad && !isLegalMaskedLoad(SrcVTy, Alignment)) ||
3741       (IsStore && !isLegalMaskedStore(SrcVTy, Alignment))) {
3742     // Scalarization
3743     APInt DemandedElts = APInt::getAllOnes(NumElem);
3744     InstructionCost MaskSplitCost =
3745         getScalarizationOverhead(MaskTy, DemandedElts, false, true);
3746     InstructionCost ScalarCompareCost = getCmpSelInstrCost(
3747         Instruction::ICmp, Type::getInt8Ty(SrcVTy->getContext()), nullptr,
3748         CmpInst::BAD_ICMP_PREDICATE, CostKind);
3749     InstructionCost BranchCost = getCFInstrCost(Instruction::Br, CostKind);
3750     InstructionCost MaskCmpCost = NumElem * (BranchCost + ScalarCompareCost);
3751     InstructionCost ValueSplitCost =
3752         getScalarizationOverhead(SrcVTy, DemandedElts, IsLoad, IsStore);
3753     InstructionCost MemopCost =
3754         NumElem * BaseT::getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
3755                                          Alignment, AddressSpace, CostKind);
3756     return MemopCost + ValueSplitCost + MaskSplitCost + MaskCmpCost;
3757   }
3758 
3759   // Legalize the type.
3760   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, SrcVTy);
3761   auto VT = TLI->getValueType(DL, SrcVTy);
3762   InstructionCost Cost = 0;
3763   if (VT.isSimple() && LT.second != VT.getSimpleVT() &&
3764       LT.second.getVectorNumElements() == NumElem)
3765     // Promotion requires extend/truncate for data and a shuffle for mask.
3766     Cost += getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVTy, None, 0, nullptr) +
3767             getShuffleCost(TTI::SK_PermuteTwoSrc, MaskTy, None, 0, nullptr);
3768 
3769   else if (LT.first * LT.second.getVectorNumElements() > NumElem) {
3770     auto *NewMaskTy = FixedVectorType::get(MaskTy->getElementType(),
3771                                            LT.second.getVectorNumElements());
3772     // Expanding requires fill mask with zeroes
3773     Cost += getShuffleCost(TTI::SK_InsertSubvector, NewMaskTy, None, 0, MaskTy);
3774   }
3775 
3776   // Pre-AVX512 - each maskmov load costs 2 + store costs ~8.
3777   if (!ST->hasAVX512())
3778     return Cost + LT.first * (IsLoad ? 2 : 8);
3779 
3780   // AVX-512 masked load/store is cheapper
3781   return Cost + LT.first;
3782 }
3783 
3784 InstructionCost X86TTIImpl::getAddressComputationCost(Type *Ty,
3785                                                       ScalarEvolution *SE,
3786                                                       const SCEV *Ptr) {
3787   // Address computations in vectorized code with non-consecutive addresses will
3788   // likely result in more instructions compared to scalar code where the
3789   // computation can more often be merged into the index mode. The resulting
3790   // extra micro-ops can significantly decrease throughput.
3791   const unsigned NumVectorInstToHideOverhead = 10;
3792 
3793   // Cost modeling of Strided Access Computation is hidden by the indexing
3794   // modes of X86 regardless of the stride value. We dont believe that there
3795   // is a difference between constant strided access in gerenal and constant
3796   // strided value which is less than or equal to 64.
3797   // Even in the case of (loop invariant) stride whose value is not known at
3798   // compile time, the address computation will not incur more than one extra
3799   // ADD instruction.
3800   if (Ty->isVectorTy() && SE) {
3801     if (!BaseT::isStridedAccess(Ptr))
3802       return NumVectorInstToHideOverhead;
3803     if (!BaseT::getConstantStrideStep(SE, Ptr))
3804       return 1;
3805   }
3806 
3807   return BaseT::getAddressComputationCost(Ty, SE, Ptr);
3808 }
3809 
3810 InstructionCost
3811 X86TTIImpl::getArithmeticReductionCost(unsigned Opcode, VectorType *ValTy,
3812                                        Optional<FastMathFlags> FMF,
3813                                        TTI::TargetCostKind CostKind) {
3814   if (TTI::requiresOrderedReduction(FMF))
3815     return BaseT::getArithmeticReductionCost(Opcode, ValTy, FMF, CostKind);
3816 
3817   // We use the Intel Architecture Code Analyzer(IACA) to measure the throughput
3818   // and make it as the cost.
3819 
3820   static const CostTblEntry SLMCostTblNoPairWise[] = {
3821     { ISD::FADD,  MVT::v2f64,   3 },
3822     { ISD::ADD,   MVT::v2i64,   5 },
3823   };
3824 
3825   static const CostTblEntry SSE2CostTblNoPairWise[] = {
3826     { ISD::FADD,  MVT::v2f64,   2 },
3827     { ISD::FADD,  MVT::v2f32,   2 },
3828     { ISD::FADD,  MVT::v4f32,   4 },
3829     { ISD::ADD,   MVT::v2i64,   2 },      // The data reported by the IACA tool is "1.6".
3830     { ISD::ADD,   MVT::v2i32,   2 }, // FIXME: chosen to be less than v4i32
3831     { ISD::ADD,   MVT::v4i32,   3 },      // The data reported by the IACA tool is "3.3".
3832     { ISD::ADD,   MVT::v2i16,   2 },      // The data reported by the IACA tool is "4.3".
3833     { ISD::ADD,   MVT::v4i16,   3 },      // The data reported by the IACA tool is "4.3".
3834     { ISD::ADD,   MVT::v8i16,   4 },      // The data reported by the IACA tool is "4.3".
3835     { ISD::ADD,   MVT::v2i8,    2 },
3836     { ISD::ADD,   MVT::v4i8,    2 },
3837     { ISD::ADD,   MVT::v8i8,    2 },
3838     { ISD::ADD,   MVT::v16i8,   3 },
3839   };
3840 
3841   static const CostTblEntry AVX1CostTblNoPairWise[] = {
3842     { ISD::FADD,  MVT::v4f64,   3 },
3843     { ISD::FADD,  MVT::v4f32,   3 },
3844     { ISD::FADD,  MVT::v8f32,   4 },
3845     { ISD::ADD,   MVT::v2i64,   1 },      // The data reported by the IACA tool is "1.5".
3846     { ISD::ADD,   MVT::v4i64,   3 },
3847     { ISD::ADD,   MVT::v8i32,   5 },
3848     { ISD::ADD,   MVT::v16i16,  5 },
3849     { ISD::ADD,   MVT::v32i8,   4 },
3850   };
3851 
3852   int ISD = TLI->InstructionOpcodeToISD(Opcode);
3853   assert(ISD && "Invalid opcode");
3854 
3855   // Before legalizing the type, give a chance to look up illegal narrow types
3856   // in the table.
3857   // FIXME: Is there a better way to do this?
3858   EVT VT = TLI->getValueType(DL, ValTy);
3859   if (VT.isSimple()) {
3860     MVT MTy = VT.getSimpleVT();
3861     if (ST->isSLM())
3862       if (const auto *Entry = CostTableLookup(SLMCostTblNoPairWise, ISD, MTy))
3863         return Entry->Cost;
3864 
3865     if (ST->hasAVX())
3866       if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
3867         return Entry->Cost;
3868 
3869     if (ST->hasSSE2())
3870       if (const auto *Entry = CostTableLookup(SSE2CostTblNoPairWise, ISD, MTy))
3871         return Entry->Cost;
3872   }
3873 
3874   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
3875 
3876   MVT MTy = LT.second;
3877 
3878   auto *ValVTy = cast<FixedVectorType>(ValTy);
3879 
3880   // Special case: vXi8 mul reductions are performed as vXi16.
3881   if (ISD == ISD::MUL && MTy.getScalarType() == MVT::i8) {
3882     auto *WideSclTy = IntegerType::get(ValVTy->getContext(), 16);
3883     auto *WideVecTy = FixedVectorType::get(WideSclTy, ValVTy->getNumElements());
3884     return getCastInstrCost(Instruction::ZExt, WideVecTy, ValTy,
3885                             TargetTransformInfo::CastContextHint::None,
3886                             CostKind) +
3887            getArithmeticReductionCost(Opcode, WideVecTy, FMF, CostKind);
3888   }
3889 
3890   InstructionCost ArithmeticCost = 0;
3891   if (LT.first != 1 && MTy.isVector() &&
3892       MTy.getVectorNumElements() < ValVTy->getNumElements()) {
3893     // Type needs to be split. We need LT.first - 1 arithmetic ops.
3894     auto *SingleOpTy = FixedVectorType::get(ValVTy->getElementType(),
3895                                             MTy.getVectorNumElements());
3896     ArithmeticCost = getArithmeticInstrCost(Opcode, SingleOpTy, CostKind);
3897     ArithmeticCost *= LT.first - 1;
3898   }
3899 
3900   if (ST->isSLM())
3901     if (const auto *Entry = CostTableLookup(SLMCostTblNoPairWise, ISD, MTy))
3902       return ArithmeticCost + Entry->Cost;
3903 
3904   if (ST->hasAVX())
3905     if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
3906       return ArithmeticCost + Entry->Cost;
3907 
3908   if (ST->hasSSE2())
3909     if (const auto *Entry = CostTableLookup(SSE2CostTblNoPairWise, ISD, MTy))
3910       return ArithmeticCost + Entry->Cost;
3911 
3912   // FIXME: These assume a naive kshift+binop lowering, which is probably
3913   // conservative in most cases.
3914   static const CostTblEntry AVX512BoolReduction[] = {
3915     { ISD::AND,  MVT::v2i1,   3 },
3916     { ISD::AND,  MVT::v4i1,   5 },
3917     { ISD::AND,  MVT::v8i1,   7 },
3918     { ISD::AND,  MVT::v16i1,  9 },
3919     { ISD::AND,  MVT::v32i1, 11 },
3920     { ISD::AND,  MVT::v64i1, 13 },
3921     { ISD::OR,   MVT::v2i1,   3 },
3922     { ISD::OR,   MVT::v4i1,   5 },
3923     { ISD::OR,   MVT::v8i1,   7 },
3924     { ISD::OR,   MVT::v16i1,  9 },
3925     { ISD::OR,   MVT::v32i1, 11 },
3926     { ISD::OR,   MVT::v64i1, 13 },
3927   };
3928 
3929   static const CostTblEntry AVX2BoolReduction[] = {
3930     { ISD::AND,  MVT::v16i16,  2 }, // vpmovmskb + cmp
3931     { ISD::AND,  MVT::v32i8,   2 }, // vpmovmskb + cmp
3932     { ISD::OR,   MVT::v16i16,  2 }, // vpmovmskb + cmp
3933     { ISD::OR,   MVT::v32i8,   2 }, // vpmovmskb + cmp
3934   };
3935 
3936   static const CostTblEntry AVX1BoolReduction[] = {
3937     { ISD::AND,  MVT::v4i64,   2 }, // vmovmskpd + cmp
3938     { ISD::AND,  MVT::v8i32,   2 }, // vmovmskps + cmp
3939     { ISD::AND,  MVT::v16i16,  4 }, // vextractf128 + vpand + vpmovmskb + cmp
3940     { ISD::AND,  MVT::v32i8,   4 }, // vextractf128 + vpand + vpmovmskb + cmp
3941     { ISD::OR,   MVT::v4i64,   2 }, // vmovmskpd + cmp
3942     { ISD::OR,   MVT::v8i32,   2 }, // vmovmskps + cmp
3943     { ISD::OR,   MVT::v16i16,  4 }, // vextractf128 + vpor + vpmovmskb + cmp
3944     { ISD::OR,   MVT::v32i8,   4 }, // vextractf128 + vpor + vpmovmskb + cmp
3945   };
3946 
3947   static const CostTblEntry SSE2BoolReduction[] = {
3948     { ISD::AND,  MVT::v2i64,   2 }, // movmskpd + cmp
3949     { ISD::AND,  MVT::v4i32,   2 }, // movmskps + cmp
3950     { ISD::AND,  MVT::v8i16,   2 }, // pmovmskb + cmp
3951     { ISD::AND,  MVT::v16i8,   2 }, // pmovmskb + cmp
3952     { ISD::OR,   MVT::v2i64,   2 }, // movmskpd + cmp
3953     { ISD::OR,   MVT::v4i32,   2 }, // movmskps + cmp
3954     { ISD::OR,   MVT::v8i16,   2 }, // pmovmskb + cmp
3955     { ISD::OR,   MVT::v16i8,   2 }, // pmovmskb + cmp
3956   };
3957 
3958   // Handle bool allof/anyof patterns.
3959   if (ValVTy->getElementType()->isIntegerTy(1)) {
3960     InstructionCost ArithmeticCost = 0;
3961     if (LT.first != 1 && MTy.isVector() &&
3962         MTy.getVectorNumElements() < ValVTy->getNumElements()) {
3963       // Type needs to be split. We need LT.first - 1 arithmetic ops.
3964       auto *SingleOpTy = FixedVectorType::get(ValVTy->getElementType(),
3965                                               MTy.getVectorNumElements());
3966       ArithmeticCost = getArithmeticInstrCost(Opcode, SingleOpTy, CostKind);
3967       ArithmeticCost *= LT.first - 1;
3968     }
3969 
3970     if (ST->hasAVX512())
3971       if (const auto *Entry = CostTableLookup(AVX512BoolReduction, ISD, MTy))
3972         return ArithmeticCost + Entry->Cost;
3973     if (ST->hasAVX2())
3974       if (const auto *Entry = CostTableLookup(AVX2BoolReduction, ISD, MTy))
3975         return ArithmeticCost + Entry->Cost;
3976     if (ST->hasAVX())
3977       if (const auto *Entry = CostTableLookup(AVX1BoolReduction, ISD, MTy))
3978         return ArithmeticCost + Entry->Cost;
3979     if (ST->hasSSE2())
3980       if (const auto *Entry = CostTableLookup(SSE2BoolReduction, ISD, MTy))
3981         return ArithmeticCost + Entry->Cost;
3982 
3983     return BaseT::getArithmeticReductionCost(Opcode, ValVTy, FMF, CostKind);
3984   }
3985 
3986   unsigned NumVecElts = ValVTy->getNumElements();
3987   unsigned ScalarSize = ValVTy->getScalarSizeInBits();
3988 
3989   // Special case power of 2 reductions where the scalar type isn't changed
3990   // by type legalization.
3991   if (!isPowerOf2_32(NumVecElts) || ScalarSize != MTy.getScalarSizeInBits())
3992     return BaseT::getArithmeticReductionCost(Opcode, ValVTy, FMF, CostKind);
3993 
3994   InstructionCost ReductionCost = 0;
3995 
3996   auto *Ty = ValVTy;
3997   if (LT.first != 1 && MTy.isVector() &&
3998       MTy.getVectorNumElements() < ValVTy->getNumElements()) {
3999     // Type needs to be split. We need LT.first - 1 arithmetic ops.
4000     Ty = FixedVectorType::get(ValVTy->getElementType(),
4001                               MTy.getVectorNumElements());
4002     ReductionCost = getArithmeticInstrCost(Opcode, Ty, CostKind);
4003     ReductionCost *= LT.first - 1;
4004     NumVecElts = MTy.getVectorNumElements();
4005   }
4006 
4007   // Now handle reduction with the legal type, taking into account size changes
4008   // at each level.
4009   while (NumVecElts > 1) {
4010     // Determine the size of the remaining vector we need to reduce.
4011     unsigned Size = NumVecElts * ScalarSize;
4012     NumVecElts /= 2;
4013     // If we're reducing from 256/512 bits, use an extract_subvector.
4014     if (Size > 128) {
4015       auto *SubTy = FixedVectorType::get(ValVTy->getElementType(), NumVecElts);
4016       ReductionCost +=
4017           getShuffleCost(TTI::SK_ExtractSubvector, Ty, None, NumVecElts, SubTy);
4018       Ty = SubTy;
4019     } else if (Size == 128) {
4020       // Reducing from 128 bits is a permute of v2f64/v2i64.
4021       FixedVectorType *ShufTy;
4022       if (ValVTy->isFloatingPointTy())
4023         ShufTy =
4024             FixedVectorType::get(Type::getDoubleTy(ValVTy->getContext()), 2);
4025       else
4026         ShufTy =
4027             FixedVectorType::get(Type::getInt64Ty(ValVTy->getContext()), 2);
4028       ReductionCost +=
4029           getShuffleCost(TTI::SK_PermuteSingleSrc, ShufTy, None, 0, nullptr);
4030     } else if (Size == 64) {
4031       // Reducing from 64 bits is a shuffle of v4f32/v4i32.
4032       FixedVectorType *ShufTy;
4033       if (ValVTy->isFloatingPointTy())
4034         ShufTy =
4035             FixedVectorType::get(Type::getFloatTy(ValVTy->getContext()), 4);
4036       else
4037         ShufTy =
4038             FixedVectorType::get(Type::getInt32Ty(ValVTy->getContext()), 4);
4039       ReductionCost +=
4040           getShuffleCost(TTI::SK_PermuteSingleSrc, ShufTy, None, 0, nullptr);
4041     } else {
4042       // Reducing from smaller size is a shift by immediate.
4043       auto *ShiftTy = FixedVectorType::get(
4044           Type::getIntNTy(ValVTy->getContext(), Size), 128 / Size);
4045       ReductionCost += getArithmeticInstrCost(
4046           Instruction::LShr, ShiftTy, CostKind,
4047           TargetTransformInfo::OK_AnyValue,
4048           TargetTransformInfo::OK_UniformConstantValue,
4049           TargetTransformInfo::OP_None, TargetTransformInfo::OP_None);
4050     }
4051 
4052     // Add the arithmetic op for this level.
4053     ReductionCost += getArithmeticInstrCost(Opcode, Ty, CostKind);
4054   }
4055 
4056   // Add the final extract element to the cost.
4057   return ReductionCost + getVectorInstrCost(Instruction::ExtractElement, Ty, 0);
4058 }
4059 
4060 InstructionCost X86TTIImpl::getMinMaxCost(Type *Ty, Type *CondTy,
4061                                           bool IsUnsigned) {
4062   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
4063 
4064   MVT MTy = LT.second;
4065 
4066   int ISD;
4067   if (Ty->isIntOrIntVectorTy()) {
4068     ISD = IsUnsigned ? ISD::UMIN : ISD::SMIN;
4069   } else {
4070     assert(Ty->isFPOrFPVectorTy() &&
4071            "Expected float point or integer vector type.");
4072     ISD = ISD::FMINNUM;
4073   }
4074 
4075   static const CostTblEntry SSE1CostTbl[] = {
4076     {ISD::FMINNUM, MVT::v4f32, 1},
4077   };
4078 
4079   static const CostTblEntry SSE2CostTbl[] = {
4080     {ISD::FMINNUM, MVT::v2f64, 1},
4081     {ISD::SMIN,    MVT::v8i16, 1},
4082     {ISD::UMIN,    MVT::v16i8, 1},
4083   };
4084 
4085   static const CostTblEntry SSE41CostTbl[] = {
4086     {ISD::SMIN,    MVT::v4i32, 1},
4087     {ISD::UMIN,    MVT::v4i32, 1},
4088     {ISD::UMIN,    MVT::v8i16, 1},
4089     {ISD::SMIN,    MVT::v16i8, 1},
4090   };
4091 
4092   static const CostTblEntry SSE42CostTbl[] = {
4093     {ISD::UMIN,    MVT::v2i64, 3}, // xor+pcmpgtq+blendvpd
4094   };
4095 
4096   static const CostTblEntry AVX1CostTbl[] = {
4097     {ISD::FMINNUM, MVT::v8f32,  1},
4098     {ISD::FMINNUM, MVT::v4f64,  1},
4099     {ISD::SMIN,    MVT::v8i32,  3},
4100     {ISD::UMIN,    MVT::v8i32,  3},
4101     {ISD::SMIN,    MVT::v16i16, 3},
4102     {ISD::UMIN,    MVT::v16i16, 3},
4103     {ISD::SMIN,    MVT::v32i8,  3},
4104     {ISD::UMIN,    MVT::v32i8,  3},
4105   };
4106 
4107   static const CostTblEntry AVX2CostTbl[] = {
4108     {ISD::SMIN,    MVT::v8i32,  1},
4109     {ISD::UMIN,    MVT::v8i32,  1},
4110     {ISD::SMIN,    MVT::v16i16, 1},
4111     {ISD::UMIN,    MVT::v16i16, 1},
4112     {ISD::SMIN,    MVT::v32i8,  1},
4113     {ISD::UMIN,    MVT::v32i8,  1},
4114   };
4115 
4116   static const CostTblEntry AVX512CostTbl[] = {
4117     {ISD::FMINNUM, MVT::v16f32, 1},
4118     {ISD::FMINNUM, MVT::v8f64,  1},
4119     {ISD::SMIN,    MVT::v2i64,  1},
4120     {ISD::UMIN,    MVT::v2i64,  1},
4121     {ISD::SMIN,    MVT::v4i64,  1},
4122     {ISD::UMIN,    MVT::v4i64,  1},
4123     {ISD::SMIN,    MVT::v8i64,  1},
4124     {ISD::UMIN,    MVT::v8i64,  1},
4125     {ISD::SMIN,    MVT::v16i32, 1},
4126     {ISD::UMIN,    MVT::v16i32, 1},
4127   };
4128 
4129   static const CostTblEntry AVX512BWCostTbl[] = {
4130     {ISD::SMIN,    MVT::v32i16, 1},
4131     {ISD::UMIN,    MVT::v32i16, 1},
4132     {ISD::SMIN,    MVT::v64i8,  1},
4133     {ISD::UMIN,    MVT::v64i8,  1},
4134   };
4135 
4136   // If we have a native MIN/MAX instruction for this type, use it.
4137   if (ST->hasBWI())
4138     if (const auto *Entry = CostTableLookup(AVX512BWCostTbl, ISD, MTy))
4139       return LT.first * Entry->Cost;
4140 
4141   if (ST->hasAVX512())
4142     if (const auto *Entry = CostTableLookup(AVX512CostTbl, ISD, MTy))
4143       return LT.first * Entry->Cost;
4144 
4145   if (ST->hasAVX2())
4146     if (const auto *Entry = CostTableLookup(AVX2CostTbl, ISD, MTy))
4147       return LT.first * Entry->Cost;
4148 
4149   if (ST->hasAVX())
4150     if (const auto *Entry = CostTableLookup(AVX1CostTbl, ISD, MTy))
4151       return LT.first * Entry->Cost;
4152 
4153   if (ST->hasSSE42())
4154     if (const auto *Entry = CostTableLookup(SSE42CostTbl, ISD, MTy))
4155       return LT.first * Entry->Cost;
4156 
4157   if (ST->hasSSE41())
4158     if (const auto *Entry = CostTableLookup(SSE41CostTbl, ISD, MTy))
4159       return LT.first * Entry->Cost;
4160 
4161   if (ST->hasSSE2())
4162     if (const auto *Entry = CostTableLookup(SSE2CostTbl, ISD, MTy))
4163       return LT.first * Entry->Cost;
4164 
4165   if (ST->hasSSE1())
4166     if (const auto *Entry = CostTableLookup(SSE1CostTbl, ISD, MTy))
4167       return LT.first * Entry->Cost;
4168 
4169   unsigned CmpOpcode;
4170   if (Ty->isFPOrFPVectorTy()) {
4171     CmpOpcode = Instruction::FCmp;
4172   } else {
4173     assert(Ty->isIntOrIntVectorTy() &&
4174            "expecting floating point or integer type for min/max reduction");
4175     CmpOpcode = Instruction::ICmp;
4176   }
4177 
4178   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4179   // Otherwise fall back to cmp+select.
4180   InstructionCost Result =
4181       getCmpSelInstrCost(CmpOpcode, Ty, CondTy, CmpInst::BAD_ICMP_PREDICATE,
4182                          CostKind) +
4183       getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
4184                          CmpInst::BAD_ICMP_PREDICATE, CostKind);
4185   return Result;
4186 }
4187 
4188 InstructionCost
4189 X86TTIImpl::getMinMaxReductionCost(VectorType *ValTy, VectorType *CondTy,
4190                                    bool IsUnsigned,
4191                                    TTI::TargetCostKind CostKind) {
4192   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
4193 
4194   MVT MTy = LT.second;
4195 
4196   int ISD;
4197   if (ValTy->isIntOrIntVectorTy()) {
4198     ISD = IsUnsigned ? ISD::UMIN : ISD::SMIN;
4199   } else {
4200     assert(ValTy->isFPOrFPVectorTy() &&
4201            "Expected float point or integer vector type.");
4202     ISD = ISD::FMINNUM;
4203   }
4204 
4205   // We use the Intel Architecture Code Analyzer(IACA) to measure the throughput
4206   // and make it as the cost.
4207 
4208   static const CostTblEntry SSE2CostTblNoPairWise[] = {
4209       {ISD::UMIN, MVT::v2i16, 5}, // need pxors to use pminsw/pmaxsw
4210       {ISD::UMIN, MVT::v4i16, 7}, // need pxors to use pminsw/pmaxsw
4211       {ISD::UMIN, MVT::v8i16, 9}, // need pxors to use pminsw/pmaxsw
4212   };
4213 
4214   static const CostTblEntry SSE41CostTblNoPairWise[] = {
4215       {ISD::SMIN, MVT::v2i16, 3}, // same as sse2
4216       {ISD::SMIN, MVT::v4i16, 5}, // same as sse2
4217       {ISD::UMIN, MVT::v2i16, 5}, // same as sse2
4218       {ISD::UMIN, MVT::v4i16, 7}, // same as sse2
4219       {ISD::SMIN, MVT::v8i16, 4}, // phminposuw+xor
4220       {ISD::UMIN, MVT::v8i16, 4}, // FIXME: umin is cheaper than umax
4221       {ISD::SMIN, MVT::v2i8,  3}, // pminsb
4222       {ISD::SMIN, MVT::v4i8,  5}, // pminsb
4223       {ISD::SMIN, MVT::v8i8,  7}, // pminsb
4224       {ISD::SMIN, MVT::v16i8, 6},
4225       {ISD::UMIN, MVT::v2i8,  3}, // same as sse2
4226       {ISD::UMIN, MVT::v4i8,  5}, // same as sse2
4227       {ISD::UMIN, MVT::v8i8,  7}, // same as sse2
4228       {ISD::UMIN, MVT::v16i8, 6}, // FIXME: umin is cheaper than umax
4229   };
4230 
4231   static const CostTblEntry AVX1CostTblNoPairWise[] = {
4232       {ISD::SMIN, MVT::v16i16, 6},
4233       {ISD::UMIN, MVT::v16i16, 6}, // FIXME: umin is cheaper than umax
4234       {ISD::SMIN, MVT::v32i8, 8},
4235       {ISD::UMIN, MVT::v32i8, 8},
4236   };
4237 
4238   static const CostTblEntry AVX512BWCostTblNoPairWise[] = {
4239       {ISD::SMIN, MVT::v32i16, 8},
4240       {ISD::UMIN, MVT::v32i16, 8}, // FIXME: umin is cheaper than umax
4241       {ISD::SMIN, MVT::v64i8, 10},
4242       {ISD::UMIN, MVT::v64i8, 10},
4243   };
4244 
4245   // Before legalizing the type, give a chance to look up illegal narrow types
4246   // in the table.
4247   // FIXME: Is there a better way to do this?
4248   EVT VT = TLI->getValueType(DL, ValTy);
4249   if (VT.isSimple()) {
4250     MVT MTy = VT.getSimpleVT();
4251     if (ST->hasBWI())
4252       if (const auto *Entry = CostTableLookup(AVX512BWCostTblNoPairWise, ISD, MTy))
4253         return Entry->Cost;
4254 
4255     if (ST->hasAVX())
4256       if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
4257         return Entry->Cost;
4258 
4259     if (ST->hasSSE41())
4260       if (const auto *Entry = CostTableLookup(SSE41CostTblNoPairWise, ISD, MTy))
4261         return Entry->Cost;
4262 
4263     if (ST->hasSSE2())
4264       if (const auto *Entry = CostTableLookup(SSE2CostTblNoPairWise, ISD, MTy))
4265         return Entry->Cost;
4266   }
4267 
4268   auto *ValVTy = cast<FixedVectorType>(ValTy);
4269   unsigned NumVecElts = ValVTy->getNumElements();
4270 
4271   auto *Ty = ValVTy;
4272   InstructionCost MinMaxCost = 0;
4273   if (LT.first != 1 && MTy.isVector() &&
4274       MTy.getVectorNumElements() < ValVTy->getNumElements()) {
4275     // Type needs to be split. We need LT.first - 1 operations ops.
4276     Ty = FixedVectorType::get(ValVTy->getElementType(),
4277                               MTy.getVectorNumElements());
4278     auto *SubCondTy = FixedVectorType::get(CondTy->getElementType(),
4279                                            MTy.getVectorNumElements());
4280     MinMaxCost = getMinMaxCost(Ty, SubCondTy, IsUnsigned);
4281     MinMaxCost *= LT.first - 1;
4282     NumVecElts = MTy.getVectorNumElements();
4283   }
4284 
4285   if (ST->hasBWI())
4286     if (const auto *Entry = CostTableLookup(AVX512BWCostTblNoPairWise, ISD, MTy))
4287       return MinMaxCost + Entry->Cost;
4288 
4289   if (ST->hasAVX())
4290     if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
4291       return MinMaxCost + Entry->Cost;
4292 
4293   if (ST->hasSSE41())
4294     if (const auto *Entry = CostTableLookup(SSE41CostTblNoPairWise, ISD, MTy))
4295       return MinMaxCost + Entry->Cost;
4296 
4297   if (ST->hasSSE2())
4298     if (const auto *Entry = CostTableLookup(SSE2CostTblNoPairWise, ISD, MTy))
4299       return MinMaxCost + Entry->Cost;
4300 
4301   unsigned ScalarSize = ValTy->getScalarSizeInBits();
4302 
4303   // Special case power of 2 reductions where the scalar type isn't changed
4304   // by type legalization.
4305   if (!isPowerOf2_32(ValVTy->getNumElements()) ||
4306       ScalarSize != MTy.getScalarSizeInBits())
4307     return BaseT::getMinMaxReductionCost(ValTy, CondTy, IsUnsigned, CostKind);
4308 
4309   // Now handle reduction with the legal type, taking into account size changes
4310   // at each level.
4311   while (NumVecElts > 1) {
4312     // Determine the size of the remaining vector we need to reduce.
4313     unsigned Size = NumVecElts * ScalarSize;
4314     NumVecElts /= 2;
4315     // If we're reducing from 256/512 bits, use an extract_subvector.
4316     if (Size > 128) {
4317       auto *SubTy = FixedVectorType::get(ValVTy->getElementType(), NumVecElts);
4318       MinMaxCost +=
4319           getShuffleCost(TTI::SK_ExtractSubvector, Ty, None, NumVecElts, SubTy);
4320       Ty = SubTy;
4321     } else if (Size == 128) {
4322       // Reducing from 128 bits is a permute of v2f64/v2i64.
4323       VectorType *ShufTy;
4324       if (ValTy->isFloatingPointTy())
4325         ShufTy =
4326             FixedVectorType::get(Type::getDoubleTy(ValTy->getContext()), 2);
4327       else
4328         ShufTy = FixedVectorType::get(Type::getInt64Ty(ValTy->getContext()), 2);
4329       MinMaxCost +=
4330           getShuffleCost(TTI::SK_PermuteSingleSrc, ShufTy, None, 0, nullptr);
4331     } else if (Size == 64) {
4332       // Reducing from 64 bits is a shuffle of v4f32/v4i32.
4333       FixedVectorType *ShufTy;
4334       if (ValTy->isFloatingPointTy())
4335         ShufTy = FixedVectorType::get(Type::getFloatTy(ValTy->getContext()), 4);
4336       else
4337         ShufTy = FixedVectorType::get(Type::getInt32Ty(ValTy->getContext()), 4);
4338       MinMaxCost +=
4339           getShuffleCost(TTI::SK_PermuteSingleSrc, ShufTy, None, 0, nullptr);
4340     } else {
4341       // Reducing from smaller size is a shift by immediate.
4342       auto *ShiftTy = FixedVectorType::get(
4343           Type::getIntNTy(ValTy->getContext(), Size), 128 / Size);
4344       MinMaxCost += getArithmeticInstrCost(
4345           Instruction::LShr, ShiftTy, TTI::TCK_RecipThroughput,
4346           TargetTransformInfo::OK_AnyValue,
4347           TargetTransformInfo::OK_UniformConstantValue,
4348           TargetTransformInfo::OP_None, TargetTransformInfo::OP_None);
4349     }
4350 
4351     // Add the arithmetic op for this level.
4352     auto *SubCondTy =
4353         FixedVectorType::get(CondTy->getElementType(), Ty->getNumElements());
4354     MinMaxCost += getMinMaxCost(Ty, SubCondTy, IsUnsigned);
4355   }
4356 
4357   // Add the final extract element to the cost.
4358   return MinMaxCost + getVectorInstrCost(Instruction::ExtractElement, Ty, 0);
4359 }
4360 
4361 /// Calculate the cost of materializing a 64-bit value. This helper
4362 /// method might only calculate a fraction of a larger immediate. Therefore it
4363 /// is valid to return a cost of ZERO.
4364 InstructionCost X86TTIImpl::getIntImmCost(int64_t Val) {
4365   if (Val == 0)
4366     return TTI::TCC_Free;
4367 
4368   if (isInt<32>(Val))
4369     return TTI::TCC_Basic;
4370 
4371   return 2 * TTI::TCC_Basic;
4372 }
4373 
4374 InstructionCost X86TTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
4375                                           TTI::TargetCostKind CostKind) {
4376   assert(Ty->isIntegerTy());
4377 
4378   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4379   if (BitSize == 0)
4380     return ~0U;
4381 
4382   // Never hoist constants larger than 128bit, because this might lead to
4383   // incorrect code generation or assertions in codegen.
4384   // Fixme: Create a cost model for types larger than i128 once the codegen
4385   // issues have been fixed.
4386   if (BitSize > 128)
4387     return TTI::TCC_Free;
4388 
4389   if (Imm == 0)
4390     return TTI::TCC_Free;
4391 
4392   // Sign-extend all constants to a multiple of 64-bit.
4393   APInt ImmVal = Imm;
4394   if (BitSize % 64 != 0)
4395     ImmVal = Imm.sext(alignTo(BitSize, 64));
4396 
4397   // Split the constant into 64-bit chunks and calculate the cost for each
4398   // chunk.
4399   InstructionCost Cost = 0;
4400   for (unsigned ShiftVal = 0; ShiftVal < BitSize; ShiftVal += 64) {
4401     APInt Tmp = ImmVal.ashr(ShiftVal).sextOrTrunc(64);
4402     int64_t Val = Tmp.getSExtValue();
4403     Cost += getIntImmCost(Val);
4404   }
4405   // We need at least one instruction to materialize the constant.
4406   return std::max<InstructionCost>(1, Cost);
4407 }
4408 
4409 InstructionCost X86TTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
4410                                               const APInt &Imm, Type *Ty,
4411                                               TTI::TargetCostKind CostKind,
4412                                               Instruction *Inst) {
4413   assert(Ty->isIntegerTy());
4414 
4415   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4416   // There is no cost model for constants with a bit size of 0. Return TCC_Free
4417   // here, so that constant hoisting will ignore this constant.
4418   if (BitSize == 0)
4419     return TTI::TCC_Free;
4420 
4421   unsigned ImmIdx = ~0U;
4422   switch (Opcode) {
4423   default:
4424     return TTI::TCC_Free;
4425   case Instruction::GetElementPtr:
4426     // Always hoist the base address of a GetElementPtr. This prevents the
4427     // creation of new constants for every base constant that gets constant
4428     // folded with the offset.
4429     if (Idx == 0)
4430       return 2 * TTI::TCC_Basic;
4431     return TTI::TCC_Free;
4432   case Instruction::Store:
4433     ImmIdx = 0;
4434     break;
4435   case Instruction::ICmp:
4436     // This is an imperfect hack to prevent constant hoisting of
4437     // compares that might be trying to check if a 64-bit value fits in
4438     // 32-bits. The backend can optimize these cases using a right shift by 32.
4439     // Ideally we would check the compare predicate here. There also other
4440     // similar immediates the backend can use shifts for.
4441     if (Idx == 1 && Imm.getBitWidth() == 64) {
4442       uint64_t ImmVal = Imm.getZExtValue();
4443       if (ImmVal == 0x100000000ULL || ImmVal == 0xffffffff)
4444         return TTI::TCC_Free;
4445     }
4446     ImmIdx = 1;
4447     break;
4448   case Instruction::And:
4449     // We support 64-bit ANDs with immediates with 32-bits of leading zeroes
4450     // by using a 32-bit operation with implicit zero extension. Detect such
4451     // immediates here as the normal path expects bit 31 to be sign extended.
4452     if (Idx == 1 && Imm.getBitWidth() == 64 && isUInt<32>(Imm.getZExtValue()))
4453       return TTI::TCC_Free;
4454     ImmIdx = 1;
4455     break;
4456   case Instruction::Add:
4457   case Instruction::Sub:
4458     // For add/sub, we can use the opposite instruction for INT32_MIN.
4459     if (Idx == 1 && Imm.getBitWidth() == 64 && Imm.getZExtValue() == 0x80000000)
4460       return TTI::TCC_Free;
4461     ImmIdx = 1;
4462     break;
4463   case Instruction::UDiv:
4464   case Instruction::SDiv:
4465   case Instruction::URem:
4466   case Instruction::SRem:
4467     // Division by constant is typically expanded later into a different
4468     // instruction sequence. This completely changes the constants.
4469     // Report them as "free" to stop ConstantHoist from marking them as opaque.
4470     return TTI::TCC_Free;
4471   case Instruction::Mul:
4472   case Instruction::Or:
4473   case Instruction::Xor:
4474     ImmIdx = 1;
4475     break;
4476   // Always return TCC_Free for the shift value of a shift instruction.
4477   case Instruction::Shl:
4478   case Instruction::LShr:
4479   case Instruction::AShr:
4480     if (Idx == 1)
4481       return TTI::TCC_Free;
4482     break;
4483   case Instruction::Trunc:
4484   case Instruction::ZExt:
4485   case Instruction::SExt:
4486   case Instruction::IntToPtr:
4487   case Instruction::PtrToInt:
4488   case Instruction::BitCast:
4489   case Instruction::PHI:
4490   case Instruction::Call:
4491   case Instruction::Select:
4492   case Instruction::Ret:
4493   case Instruction::Load:
4494     break;
4495   }
4496 
4497   if (Idx == ImmIdx) {
4498     int NumConstants = divideCeil(BitSize, 64);
4499     InstructionCost Cost = X86TTIImpl::getIntImmCost(Imm, Ty, CostKind);
4500     return (Cost <= NumConstants * TTI::TCC_Basic)
4501                ? static_cast<int>(TTI::TCC_Free)
4502                : Cost;
4503   }
4504 
4505   return X86TTIImpl::getIntImmCost(Imm, Ty, CostKind);
4506 }
4507 
4508 InstructionCost X86TTIImpl::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
4509                                                 const APInt &Imm, Type *Ty,
4510                                                 TTI::TargetCostKind CostKind) {
4511   assert(Ty->isIntegerTy());
4512 
4513   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4514   // There is no cost model for constants with a bit size of 0. Return TCC_Free
4515   // here, so that constant hoisting will ignore this constant.
4516   if (BitSize == 0)
4517     return TTI::TCC_Free;
4518 
4519   switch (IID) {
4520   default:
4521     return TTI::TCC_Free;
4522   case Intrinsic::sadd_with_overflow:
4523   case Intrinsic::uadd_with_overflow:
4524   case Intrinsic::ssub_with_overflow:
4525   case Intrinsic::usub_with_overflow:
4526   case Intrinsic::smul_with_overflow:
4527   case Intrinsic::umul_with_overflow:
4528     if ((Idx == 1) && Imm.getBitWidth() <= 64 && isInt<32>(Imm.getSExtValue()))
4529       return TTI::TCC_Free;
4530     break;
4531   case Intrinsic::experimental_stackmap:
4532     if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
4533       return TTI::TCC_Free;
4534     break;
4535   case Intrinsic::experimental_patchpoint_void:
4536   case Intrinsic::experimental_patchpoint_i64:
4537     if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
4538       return TTI::TCC_Free;
4539     break;
4540   }
4541   return X86TTIImpl::getIntImmCost(Imm, Ty, CostKind);
4542 }
4543 
4544 InstructionCost X86TTIImpl::getCFInstrCost(unsigned Opcode,
4545                                            TTI::TargetCostKind CostKind,
4546                                            const Instruction *I) {
4547   if (CostKind != TTI::TCK_RecipThroughput)
4548     return Opcode == Instruction::PHI ? 0 : 1;
4549   // Branches are assumed to be predicted.
4550   return 0;
4551 }
4552 
4553 int X86TTIImpl::getGatherOverhead() const {
4554   // Some CPUs have more overhead for gather. The specified overhead is relative
4555   // to the Load operation. "2" is the number provided by Intel architects. This
4556   // parameter is used for cost estimation of Gather Op and comparison with
4557   // other alternatives.
4558   // TODO: Remove the explicit hasAVX512()?, That would mean we would only
4559   // enable gather with a -march.
4560   if (ST->hasAVX512() || (ST->hasAVX2() && ST->hasFastGather()))
4561     return 2;
4562 
4563   return 1024;
4564 }
4565 
4566 int X86TTIImpl::getScatterOverhead() const {
4567   if (ST->hasAVX512())
4568     return 2;
4569 
4570   return 1024;
4571 }
4572 
4573 // Return an average cost of Gather / Scatter instruction, maybe improved later.
4574 // FIXME: Add TargetCostKind support.
4575 InstructionCost X86TTIImpl::getGSVectorCost(unsigned Opcode, Type *SrcVTy,
4576                                             const Value *Ptr, Align Alignment,
4577                                             unsigned AddressSpace) {
4578 
4579   assert(isa<VectorType>(SrcVTy) && "Unexpected type in getGSVectorCost");
4580   unsigned VF = cast<FixedVectorType>(SrcVTy)->getNumElements();
4581 
4582   // Try to reduce index size from 64 bit (default for GEP)
4583   // to 32. It is essential for VF 16. If the index can't be reduced to 32, the
4584   // operation will use 16 x 64 indices which do not fit in a zmm and needs
4585   // to split. Also check that the base pointer is the same for all lanes,
4586   // and that there's at most one variable index.
4587   auto getIndexSizeInBits = [](const Value *Ptr, const DataLayout &DL) {
4588     unsigned IndexSize = DL.getPointerSizeInBits();
4589     const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4590     if (IndexSize < 64 || !GEP)
4591       return IndexSize;
4592 
4593     unsigned NumOfVarIndices = 0;
4594     const Value *Ptrs = GEP->getPointerOperand();
4595     if (Ptrs->getType()->isVectorTy() && !getSplatValue(Ptrs))
4596       return IndexSize;
4597     for (unsigned i = 1; i < GEP->getNumOperands(); ++i) {
4598       if (isa<Constant>(GEP->getOperand(i)))
4599         continue;
4600       Type *IndxTy = GEP->getOperand(i)->getType();
4601       if (auto *IndexVTy = dyn_cast<VectorType>(IndxTy))
4602         IndxTy = IndexVTy->getElementType();
4603       if ((IndxTy->getPrimitiveSizeInBits() == 64 &&
4604           !isa<SExtInst>(GEP->getOperand(i))) ||
4605          ++NumOfVarIndices > 1)
4606         return IndexSize; // 64
4607     }
4608     return (unsigned)32;
4609   };
4610 
4611   // Trying to reduce IndexSize to 32 bits for vector 16.
4612   // By default the IndexSize is equal to pointer size.
4613   unsigned IndexSize = (ST->hasAVX512() && VF >= 16)
4614                            ? getIndexSizeInBits(Ptr, DL)
4615                            : DL.getPointerSizeInBits();
4616 
4617   auto *IndexVTy = FixedVectorType::get(
4618       IntegerType::get(SrcVTy->getContext(), IndexSize), VF);
4619   std::pair<InstructionCost, MVT> IdxsLT =
4620       TLI->getTypeLegalizationCost(DL, IndexVTy);
4621   std::pair<InstructionCost, MVT> SrcLT =
4622       TLI->getTypeLegalizationCost(DL, SrcVTy);
4623   InstructionCost::CostType SplitFactor =
4624       *std::max(IdxsLT.first, SrcLT.first).getValue();
4625   if (SplitFactor > 1) {
4626     // Handle splitting of vector of pointers
4627     auto *SplitSrcTy =
4628         FixedVectorType::get(SrcVTy->getScalarType(), VF / SplitFactor);
4629     return SplitFactor * getGSVectorCost(Opcode, SplitSrcTy, Ptr, Alignment,
4630                                          AddressSpace);
4631   }
4632 
4633   // The gather / scatter cost is given by Intel architects. It is a rough
4634   // number since we are looking at one instruction in a time.
4635   const int GSOverhead = (Opcode == Instruction::Load)
4636                              ? getGatherOverhead()
4637                              : getScatterOverhead();
4638   return GSOverhead + VF * getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
4639                                            MaybeAlign(Alignment), AddressSpace,
4640                                            TTI::TCK_RecipThroughput);
4641 }
4642 
4643 /// Return the cost of full scalarization of gather / scatter operation.
4644 ///
4645 /// Opcode - Load or Store instruction.
4646 /// SrcVTy - The type of the data vector that should be gathered or scattered.
4647 /// VariableMask - The mask is non-constant at compile time.
4648 /// Alignment - Alignment for one element.
4649 /// AddressSpace - pointer[s] address space.
4650 ///
4651 /// FIXME: Add TargetCostKind support.
4652 InstructionCost X86TTIImpl::getGSScalarCost(unsigned Opcode, Type *SrcVTy,
4653                                             bool VariableMask, Align Alignment,
4654                                             unsigned AddressSpace) {
4655   unsigned VF = cast<FixedVectorType>(SrcVTy)->getNumElements();
4656   APInt DemandedElts = APInt::getAllOnes(VF);
4657   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4658 
4659   InstructionCost MaskUnpackCost = 0;
4660   if (VariableMask) {
4661     auto *MaskTy =
4662         FixedVectorType::get(Type::getInt1Ty(SrcVTy->getContext()), VF);
4663     MaskUnpackCost =
4664         getScalarizationOverhead(MaskTy, DemandedElts, false, true);
4665     InstructionCost ScalarCompareCost = getCmpSelInstrCost(
4666         Instruction::ICmp, Type::getInt1Ty(SrcVTy->getContext()), nullptr,
4667         CmpInst::BAD_ICMP_PREDICATE, CostKind);
4668     InstructionCost BranchCost = getCFInstrCost(Instruction::Br, CostKind);
4669     MaskUnpackCost += VF * (BranchCost + ScalarCompareCost);
4670   }
4671 
4672   // The cost of the scalar loads/stores.
4673   InstructionCost MemoryOpCost =
4674       VF * getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
4675                            MaybeAlign(Alignment), AddressSpace, CostKind);
4676 
4677   InstructionCost InsertExtractCost = 0;
4678   if (Opcode == Instruction::Load)
4679     for (unsigned i = 0; i < VF; ++i)
4680       // Add the cost of inserting each scalar load into the vector
4681       InsertExtractCost +=
4682         getVectorInstrCost(Instruction::InsertElement, SrcVTy, i);
4683   else
4684     for (unsigned i = 0; i < VF; ++i)
4685       // Add the cost of extracting each element out of the data vector
4686       InsertExtractCost +=
4687         getVectorInstrCost(Instruction::ExtractElement, SrcVTy, i);
4688 
4689   return MemoryOpCost + MaskUnpackCost + InsertExtractCost;
4690 }
4691 
4692 /// Calculate the cost of Gather / Scatter operation
4693 InstructionCost X86TTIImpl::getGatherScatterOpCost(
4694     unsigned Opcode, Type *SrcVTy, const Value *Ptr, bool VariableMask,
4695     Align Alignment, TTI::TargetCostKind CostKind,
4696     const Instruction *I = nullptr) {
4697   if (CostKind != TTI::TCK_RecipThroughput) {
4698     if ((Opcode == Instruction::Load &&
4699          isLegalMaskedGather(SrcVTy, Align(Alignment))) ||
4700         (Opcode == Instruction::Store &&
4701          isLegalMaskedScatter(SrcVTy, Align(Alignment))))
4702       return 1;
4703     return BaseT::getGatherScatterOpCost(Opcode, SrcVTy, Ptr, VariableMask,
4704                                          Alignment, CostKind, I);
4705   }
4706 
4707   assert(SrcVTy->isVectorTy() && "Unexpected data type for Gather/Scatter");
4708   PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
4709   if (!PtrTy && Ptr->getType()->isVectorTy())
4710     PtrTy = dyn_cast<PointerType>(
4711         cast<VectorType>(Ptr->getType())->getElementType());
4712   assert(PtrTy && "Unexpected type for Ptr argument");
4713   unsigned AddressSpace = PtrTy->getAddressSpace();
4714 
4715   if ((Opcode == Instruction::Load &&
4716        !isLegalMaskedGather(SrcVTy, Align(Alignment))) ||
4717       (Opcode == Instruction::Store &&
4718        !isLegalMaskedScatter(SrcVTy, Align(Alignment))))
4719     return getGSScalarCost(Opcode, SrcVTy, VariableMask, Alignment,
4720                            AddressSpace);
4721 
4722   return getGSVectorCost(Opcode, SrcVTy, Ptr, Alignment, AddressSpace);
4723 }
4724 
4725 bool X86TTIImpl::isLSRCostLess(TargetTransformInfo::LSRCost &C1,
4726                                TargetTransformInfo::LSRCost &C2) {
4727     // X86 specific here are "instruction number 1st priority".
4728     return std::tie(C1.Insns, C1.NumRegs, C1.AddRecCost,
4729                     C1.NumIVMuls, C1.NumBaseAdds,
4730                     C1.ScaleCost, C1.ImmCost, C1.SetupCost) <
4731            std::tie(C2.Insns, C2.NumRegs, C2.AddRecCost,
4732                     C2.NumIVMuls, C2.NumBaseAdds,
4733                     C2.ScaleCost, C2.ImmCost, C2.SetupCost);
4734 }
4735 
4736 bool X86TTIImpl::canMacroFuseCmp() {
4737   return ST->hasMacroFusion() || ST->hasBranchFusion();
4738 }
4739 
4740 bool X86TTIImpl::isLegalMaskedLoad(Type *DataTy, Align Alignment) {
4741   if (!ST->hasAVX())
4742     return false;
4743 
4744   // The backend can't handle a single element vector.
4745   if (isa<VectorType>(DataTy) &&
4746       cast<FixedVectorType>(DataTy)->getNumElements() == 1)
4747     return false;
4748   Type *ScalarTy = DataTy->getScalarType();
4749 
4750   if (ScalarTy->isPointerTy())
4751     return true;
4752 
4753   if (ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
4754     return true;
4755 
4756   if (ScalarTy->isHalfTy() && ST->hasBWI() && ST->hasFP16())
4757     return true;
4758 
4759   if (!ScalarTy->isIntegerTy())
4760     return false;
4761 
4762   unsigned IntWidth = ScalarTy->getIntegerBitWidth();
4763   return IntWidth == 32 || IntWidth == 64 ||
4764          ((IntWidth == 8 || IntWidth == 16) && ST->hasBWI());
4765 }
4766 
4767 bool X86TTIImpl::isLegalMaskedStore(Type *DataType, Align Alignment) {
4768   return isLegalMaskedLoad(DataType, Alignment);
4769 }
4770 
4771 bool X86TTIImpl::isLegalNTLoad(Type *DataType, Align Alignment) {
4772   unsigned DataSize = DL.getTypeStoreSize(DataType);
4773   // The only supported nontemporal loads are for aligned vectors of 16 or 32
4774   // bytes.  Note that 32-byte nontemporal vector loads are supported by AVX2
4775   // (the equivalent stores only require AVX).
4776   if (Alignment >= DataSize && (DataSize == 16 || DataSize == 32))
4777     return DataSize == 16 ?  ST->hasSSE1() : ST->hasAVX2();
4778 
4779   return false;
4780 }
4781 
4782 bool X86TTIImpl::isLegalNTStore(Type *DataType, Align Alignment) {
4783   unsigned DataSize = DL.getTypeStoreSize(DataType);
4784 
4785   // SSE4A supports nontemporal stores of float and double at arbitrary
4786   // alignment.
4787   if (ST->hasSSE4A() && (DataType->isFloatTy() || DataType->isDoubleTy()))
4788     return true;
4789 
4790   // Besides the SSE4A subtarget exception above, only aligned stores are
4791   // available nontemporaly on any other subtarget.  And only stores with a size
4792   // of 4..32 bytes (powers of 2, only) are permitted.
4793   if (Alignment < DataSize || DataSize < 4 || DataSize > 32 ||
4794       !isPowerOf2_32(DataSize))
4795     return false;
4796 
4797   // 32-byte vector nontemporal stores are supported by AVX (the equivalent
4798   // loads require AVX2).
4799   if (DataSize == 32)
4800     return ST->hasAVX();
4801   else if (DataSize == 16)
4802     return ST->hasSSE1();
4803   return true;
4804 }
4805 
4806 bool X86TTIImpl::isLegalMaskedExpandLoad(Type *DataTy) {
4807   if (!isa<VectorType>(DataTy))
4808     return false;
4809 
4810   if (!ST->hasAVX512())
4811     return false;
4812 
4813   // The backend can't handle a single element vector.
4814   if (cast<FixedVectorType>(DataTy)->getNumElements() == 1)
4815     return false;
4816 
4817   Type *ScalarTy = cast<VectorType>(DataTy)->getElementType();
4818 
4819   if (ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
4820     return true;
4821 
4822   if (!ScalarTy->isIntegerTy())
4823     return false;
4824 
4825   unsigned IntWidth = ScalarTy->getIntegerBitWidth();
4826   return IntWidth == 32 || IntWidth == 64 ||
4827          ((IntWidth == 8 || IntWidth == 16) && ST->hasVBMI2());
4828 }
4829 
4830 bool X86TTIImpl::isLegalMaskedCompressStore(Type *DataTy) {
4831   return isLegalMaskedExpandLoad(DataTy);
4832 }
4833 
4834 bool X86TTIImpl::isLegalMaskedGather(Type *DataTy, Align Alignment) {
4835   // Some CPUs have better gather performance than others.
4836   // TODO: Remove the explicit ST->hasAVX512()?, That would mean we would only
4837   // enable gather with a -march.
4838   if (!(ST->hasAVX512() || (ST->hasFastGather() && ST->hasAVX2())))
4839     return false;
4840 
4841   // This function is called now in two cases: from the Loop Vectorizer
4842   // and from the Scalarizer.
4843   // When the Loop Vectorizer asks about legality of the feature,
4844   // the vectorization factor is not calculated yet. The Loop Vectorizer
4845   // sends a scalar type and the decision is based on the width of the
4846   // scalar element.
4847   // Later on, the cost model will estimate usage this intrinsic based on
4848   // the vector type.
4849   // The Scalarizer asks again about legality. It sends a vector type.
4850   // In this case we can reject non-power-of-2 vectors.
4851   // We also reject single element vectors as the type legalizer can't
4852   // scalarize it.
4853   if (auto *DataVTy = dyn_cast<FixedVectorType>(DataTy)) {
4854     unsigned NumElts = DataVTy->getNumElements();
4855     if (NumElts == 1)
4856       return false;
4857     // Gather / Scatter for vector 2 is not profitable on KNL / SKX
4858     // Vector-4 of gather/scatter instruction does not exist on KNL.
4859     // We can extend it to 8 elements, but zeroing upper bits of
4860     // the mask vector will add more instructions. Right now we give the scalar
4861     // cost of vector-4 for KNL. TODO: Check, maybe the gather/scatter
4862     // instruction is better in the VariableMask case.
4863     if (ST->hasAVX512() && (NumElts == 2 || (NumElts == 4 && !ST->hasVLX())))
4864       return false;
4865   }
4866   Type *ScalarTy = DataTy->getScalarType();
4867   if (ScalarTy->isPointerTy())
4868     return true;
4869 
4870   if (ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
4871     return true;
4872 
4873   if (!ScalarTy->isIntegerTy())
4874     return false;
4875 
4876   unsigned IntWidth = ScalarTy->getIntegerBitWidth();
4877   return IntWidth == 32 || IntWidth == 64;
4878 }
4879 
4880 bool X86TTIImpl::isLegalMaskedScatter(Type *DataType, Align Alignment) {
4881   // AVX2 doesn't support scatter
4882   if (!ST->hasAVX512())
4883     return false;
4884   return isLegalMaskedGather(DataType, Alignment);
4885 }
4886 
4887 bool X86TTIImpl::hasDivRemOp(Type *DataType, bool IsSigned) {
4888   EVT VT = TLI->getValueType(DL, DataType);
4889   return TLI->isOperationLegal(IsSigned ? ISD::SDIVREM : ISD::UDIVREM, VT);
4890 }
4891 
4892 bool X86TTIImpl::isFCmpOrdCheaperThanFCmpZero(Type *Ty) {
4893   return false;
4894 }
4895 
4896 bool X86TTIImpl::areInlineCompatible(const Function *Caller,
4897                                      const Function *Callee) const {
4898   const TargetMachine &TM = getTLI()->getTargetMachine();
4899 
4900   // Work this as a subsetting of subtarget features.
4901   const FeatureBitset &CallerBits =
4902       TM.getSubtargetImpl(*Caller)->getFeatureBits();
4903   const FeatureBitset &CalleeBits =
4904       TM.getSubtargetImpl(*Callee)->getFeatureBits();
4905 
4906   FeatureBitset RealCallerBits = CallerBits & ~InlineFeatureIgnoreList;
4907   FeatureBitset RealCalleeBits = CalleeBits & ~InlineFeatureIgnoreList;
4908   return (RealCallerBits & RealCalleeBits) == RealCalleeBits;
4909 }
4910 
4911 bool X86TTIImpl::areFunctionArgsABICompatible(
4912     const Function *Caller, const Function *Callee,
4913     SmallPtrSetImpl<Argument *> &Args) const {
4914   if (!BaseT::areFunctionArgsABICompatible(Caller, Callee, Args))
4915     return false;
4916 
4917   // If we get here, we know the target features match. If one function
4918   // considers 512-bit vectors legal and the other does not, consider them
4919   // incompatible.
4920   const TargetMachine &TM = getTLI()->getTargetMachine();
4921 
4922   if (TM.getSubtarget<X86Subtarget>(*Caller).useAVX512Regs() ==
4923       TM.getSubtarget<X86Subtarget>(*Callee).useAVX512Regs())
4924     return true;
4925 
4926   // Consider the arguments compatible if they aren't vectors or aggregates.
4927   // FIXME: Look at the size of vectors.
4928   // FIXME: Look at the element types of aggregates to see if there are vectors.
4929   // FIXME: The API of this function seems intended to allow arguments
4930   // to be removed from the set, but the caller doesn't check if the set
4931   // becomes empty so that may not work in practice.
4932   return llvm::none_of(Args, [](Argument *A) {
4933     auto *EltTy = cast<PointerType>(A->getType())->getElementType();
4934     return EltTy->isVectorTy() || EltTy->isAggregateType();
4935   });
4936 }
4937 
4938 X86TTIImpl::TTI::MemCmpExpansionOptions
4939 X86TTIImpl::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const {
4940   TTI::MemCmpExpansionOptions Options;
4941   Options.MaxNumLoads = TLI->getMaxExpandSizeMemcmp(OptSize);
4942   Options.NumLoadsPerBlock = 2;
4943   // All GPR and vector loads can be unaligned.
4944   Options.AllowOverlappingLoads = true;
4945   if (IsZeroCmp) {
4946     // Only enable vector loads for equality comparison. Right now the vector
4947     // version is not as fast for three way compare (see #33329).
4948     const unsigned PreferredWidth = ST->getPreferVectorWidth();
4949     if (PreferredWidth >= 512 && ST->hasAVX512()) Options.LoadSizes.push_back(64);
4950     if (PreferredWidth >= 256 && ST->hasAVX()) Options.LoadSizes.push_back(32);
4951     if (PreferredWidth >= 128 && ST->hasSSE2()) Options.LoadSizes.push_back(16);
4952   }
4953   if (ST->is64Bit()) {
4954     Options.LoadSizes.push_back(8);
4955   }
4956   Options.LoadSizes.push_back(4);
4957   Options.LoadSizes.push_back(2);
4958   Options.LoadSizes.push_back(1);
4959   return Options;
4960 }
4961 
4962 bool X86TTIImpl::enableInterleavedAccessVectorization() {
4963   // TODO: We expect this to be beneficial regardless of arch,
4964   // but there are currently some unexplained performance artifacts on Atom.
4965   // As a temporary solution, disable on Atom.
4966   return !(ST->isAtom());
4967 }
4968 
4969 // Get estimation for interleaved load/store operations for AVX2.
4970 // \p Factor is the interleaved-access factor (stride) - number of
4971 // (interleaved) elements in the group.
4972 // \p Indices contains the indices for a strided load: when the
4973 // interleaved load has gaps they indicate which elements are used.
4974 // If Indices is empty (or if the number of indices is equal to the size
4975 // of the interleaved-access as given in \p Factor) the access has no gaps.
4976 //
4977 // As opposed to AVX-512, AVX2 does not have generic shuffles that allow
4978 // computing the cost using a generic formula as a function of generic
4979 // shuffles. We therefore use a lookup table instead, filled according to
4980 // the instruction sequences that codegen currently generates.
4981 InstructionCost X86TTIImpl::getInterleavedMemoryOpCostAVX2(
4982     unsigned Opcode, FixedVectorType *VecTy, unsigned Factor,
4983     ArrayRef<unsigned> Indices, Align Alignment, unsigned AddressSpace,
4984     TTI::TargetCostKind CostKind, bool UseMaskForCond, bool UseMaskForGaps) {
4985 
4986   if (UseMaskForCond || UseMaskForGaps)
4987     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
4988                                              Alignment, AddressSpace, CostKind,
4989                                              UseMaskForCond, UseMaskForGaps);
4990 
4991   // We currently Support only fully-interleaved groups, with no gaps.
4992   // TODO: Support also strided loads (interleaved-groups with gaps).
4993   if (Indices.size() && Indices.size() != Factor)
4994     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
4995                                              Alignment, AddressSpace, CostKind);
4996 
4997   // VecTy for interleave memop is <VF*Factor x Elt>.
4998   // So, for VF=4, Interleave Factor = 3, Element type = i32 we have
4999   // VecTy = <12 x i32>.
5000   MVT LegalVT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
5001 
5002   // This function can be called with VecTy=<6xi128>, Factor=3, in which case
5003   // the VF=2, while v2i128 is an unsupported MVT vector type
5004   // (see MachineValueType.h::getVectorVT()).
5005   if (!LegalVT.isVector())
5006     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
5007                                              Alignment, AddressSpace, CostKind);
5008 
5009   unsigned VF = VecTy->getNumElements() / Factor;
5010   Type *ScalarTy = VecTy->getElementType();
5011   // Deduplicate entries, model floats/pointers as appropriately-sized integers.
5012   if (!ScalarTy->isIntegerTy())
5013     ScalarTy =
5014         Type::getIntNTy(ScalarTy->getContext(), DL.getTypeSizeInBits(ScalarTy));
5015 
5016   // Get the cost of all the memory operations.
5017   InstructionCost MemOpCosts = getMemoryOpCost(
5018       Opcode, VecTy, MaybeAlign(Alignment), AddressSpace, CostKind);
5019 
5020   auto *VT = FixedVectorType::get(ScalarTy, VF);
5021   EVT ETy = TLI->getValueType(DL, VT);
5022   if (!ETy.isSimple())
5023     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
5024                                              Alignment, AddressSpace, CostKind);
5025 
5026   // TODO: Complete for other data-types and strides.
5027   // Each combination of Stride, element bit width and VF results in a different
5028   // sequence; The cost tables are therefore accessed with:
5029   // Factor (stride) and VectorType=VFxiN.
5030   // The Cost accounts only for the shuffle sequence;
5031   // The cost of the loads/stores is accounted for separately.
5032   //
5033   static const CostTblEntry AVX2InterleavedLoadTbl[] = {
5034       {2, MVT::v4i64, 6}, // (load 8i64 and) deinterleave into 2 x 4i64
5035 
5036       {3, MVT::v2i8, 10},  // (load 6i8 and) deinterleave into 3 x 2i8
5037       {3, MVT::v4i8, 4},   // (load 12i8 and) deinterleave into 3 x 4i8
5038       {3, MVT::v8i8, 9},   // (load 24i8 and) deinterleave into 3 x 8i8
5039       {3, MVT::v16i8, 11}, // (load 48i8 and) deinterleave into 3 x 16i8
5040       {3, MVT::v32i8, 13}, // (load 96i8 and) deinterleave into 3 x 32i8
5041 
5042       {3, MVT::v8i32, 17}, // (load 24i32 and) deinterleave into 3 x 8i32
5043 
5044       {4, MVT::v2i8, 12},  // (load 8i8 and) deinterleave into 4 x 2i8
5045       {4, MVT::v4i8, 4},   // (load 16i8 and) deinterleave into 4 x 4i8
5046       {4, MVT::v8i8, 20},  // (load 32i8 and) deinterleave into 4 x 8i8
5047       {4, MVT::v16i8, 39}, // (load 64i8 and) deinterleave into 4 x 16i8
5048       {4, MVT::v32i8, 80}, // (load 128i8 and) deinterleave into 4 x 32i8
5049 
5050       {8, MVT::v8i32, 40} // (load 64i32 and) deinterleave into 8 x 8i32
5051   };
5052 
5053   static const CostTblEntry AVX2InterleavedStoreTbl[] = {
5054       {2, MVT::v4i64, 6}, // interleave 2 x 4i64 into 8i64 (and store)
5055 
5056       {3, MVT::v2i8, 7},   // interleave 3 x 2i8 into 6i8 (and store)
5057       {3, MVT::v4i8, 8},   // interleave 3 x 4i8 into 12i8 (and store)
5058       {3, MVT::v8i8, 11},  // interleave 3 x 8i8 into 24i8 (and store)
5059       {3, MVT::v16i8, 11}, // interleave 3 x 16i8 into 48i8 (and store)
5060       {3, MVT::v32i8, 13}, // interleave 3 x 32i8 into 96i8 (and store)
5061 
5062       {4, MVT::v2i8, 12},  // interleave 4 x 2i8 into 8i8 (and store)
5063       {4, MVT::v4i8, 9},   // interleave 4 x 4i8 into 16i8 (and store)
5064       {4, MVT::v8i8, 10},  // interleave 4 x 8i8 into 32i8 (and store)
5065       {4, MVT::v16i8, 10}, // interleave 4 x 16i8 into 64i8 (and store)
5066       {4, MVT::v32i8, 12}  // interleave 4 x 32i8 into 128i8 (and store)
5067   };
5068 
5069   if (Opcode == Instruction::Load) {
5070     if (const auto *Entry =
5071             CostTableLookup(AVX2InterleavedLoadTbl, Factor, ETy.getSimpleVT()))
5072       return MemOpCosts + Entry->Cost;
5073   } else {
5074     assert(Opcode == Instruction::Store &&
5075            "Expected Store Instruction at this  point");
5076     if (const auto *Entry =
5077             CostTableLookup(AVX2InterleavedStoreTbl, Factor, ETy.getSimpleVT()))
5078       return MemOpCosts + Entry->Cost;
5079   }
5080 
5081   return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
5082                                            Alignment, AddressSpace, CostKind);
5083 }
5084 
5085 // Get estimation for interleaved load/store operations and strided load.
5086 // \p Indices contains indices for strided load.
5087 // \p Factor - the factor of interleaving.
5088 // AVX-512 provides 3-src shuffles that significantly reduces the cost.
5089 InstructionCost X86TTIImpl::getInterleavedMemoryOpCostAVX512(
5090     unsigned Opcode, FixedVectorType *VecTy, unsigned Factor,
5091     ArrayRef<unsigned> Indices, Align Alignment, unsigned AddressSpace,
5092     TTI::TargetCostKind CostKind, bool UseMaskForCond, bool UseMaskForGaps) {
5093 
5094   if (UseMaskForCond || UseMaskForGaps)
5095     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
5096                                              Alignment, AddressSpace, CostKind,
5097                                              UseMaskForCond, UseMaskForGaps);
5098 
5099   // VecTy for interleave memop is <VF*Factor x Elt>.
5100   // So, for VF=4, Interleave Factor = 3, Element type = i32 we have
5101   // VecTy = <12 x i32>.
5102 
5103   // Calculate the number of memory operations (NumOfMemOps), required
5104   // for load/store the VecTy.
5105   MVT LegalVT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
5106   unsigned VecTySize = DL.getTypeStoreSize(VecTy);
5107   unsigned LegalVTSize = LegalVT.getStoreSize();
5108   unsigned NumOfMemOps = (VecTySize + LegalVTSize - 1) / LegalVTSize;
5109 
5110   // Get the cost of one memory operation.
5111   auto *SingleMemOpTy = FixedVectorType::get(VecTy->getElementType(),
5112                                              LegalVT.getVectorNumElements());
5113   InstructionCost MemOpCost = getMemoryOpCost(
5114       Opcode, SingleMemOpTy, MaybeAlign(Alignment), AddressSpace, CostKind);
5115 
5116   unsigned VF = VecTy->getNumElements() / Factor;
5117   MVT VT = MVT::getVectorVT(MVT::getVT(VecTy->getScalarType()), VF);
5118 
5119   if (Opcode == Instruction::Load) {
5120     // The tables (AVX512InterleavedLoadTbl and AVX512InterleavedStoreTbl)
5121     // contain the cost of the optimized shuffle sequence that the
5122     // X86InterleavedAccess pass will generate.
5123     // The cost of loads and stores are computed separately from the table.
5124 
5125     // X86InterleavedAccess support only the following interleaved-access group.
5126     static const CostTblEntry AVX512InterleavedLoadTbl[] = {
5127         {3, MVT::v16i8, 12}, //(load 48i8 and) deinterleave into 3 x 16i8
5128         {3, MVT::v32i8, 14}, //(load 96i8 and) deinterleave into 3 x 32i8
5129         {3, MVT::v64i8, 22}, //(load 96i8 and) deinterleave into 3 x 32i8
5130     };
5131 
5132     if (const auto *Entry =
5133             CostTableLookup(AVX512InterleavedLoadTbl, Factor, VT))
5134       return NumOfMemOps * MemOpCost + Entry->Cost;
5135     //If an entry does not exist, fallback to the default implementation.
5136 
5137     // Kind of shuffle depends on number of loaded values.
5138     // If we load the entire data in one register, we can use a 1-src shuffle.
5139     // Otherwise, we'll merge 2 sources in each operation.
5140     TTI::ShuffleKind ShuffleKind =
5141         (NumOfMemOps > 1) ? TTI::SK_PermuteTwoSrc : TTI::SK_PermuteSingleSrc;
5142 
5143     InstructionCost ShuffleCost =
5144         getShuffleCost(ShuffleKind, SingleMemOpTy, None, 0, nullptr);
5145 
5146     unsigned NumOfLoadsInInterleaveGrp =
5147         Indices.size() ? Indices.size() : Factor;
5148     auto *ResultTy = FixedVectorType::get(VecTy->getElementType(),
5149                                           VecTy->getNumElements() / Factor);
5150     InstructionCost NumOfResults =
5151         getTLI()->getTypeLegalizationCost(DL, ResultTy).first *
5152         NumOfLoadsInInterleaveGrp;
5153 
5154     // About a half of the loads may be folded in shuffles when we have only
5155     // one result. If we have more than one result, we do not fold loads at all.
5156     unsigned NumOfUnfoldedLoads =
5157         NumOfResults > 1 ? NumOfMemOps : NumOfMemOps / 2;
5158 
5159     // Get a number of shuffle operations per result.
5160     unsigned NumOfShufflesPerResult =
5161         std::max((unsigned)1, (unsigned)(NumOfMemOps - 1));
5162 
5163     // The SK_MergeTwoSrc shuffle clobbers one of src operands.
5164     // When we have more than one destination, we need additional instructions
5165     // to keep sources.
5166     InstructionCost NumOfMoves = 0;
5167     if (NumOfResults > 1 && ShuffleKind == TTI::SK_PermuteTwoSrc)
5168       NumOfMoves = NumOfResults * NumOfShufflesPerResult / 2;
5169 
5170     InstructionCost Cost = NumOfResults * NumOfShufflesPerResult * ShuffleCost +
5171                            NumOfUnfoldedLoads * MemOpCost + NumOfMoves;
5172 
5173     return Cost;
5174   }
5175 
5176   // Store.
5177   assert(Opcode == Instruction::Store &&
5178          "Expected Store Instruction at this  point");
5179   // X86InterleavedAccess support only the following interleaved-access group.
5180   static const CostTblEntry AVX512InterleavedStoreTbl[] = {
5181       {3, MVT::v16i8, 12}, // interleave 3 x 16i8 into 48i8 (and store)
5182       {3, MVT::v32i8, 14}, // interleave 3 x 32i8 into 96i8 (and store)
5183       {3, MVT::v64i8, 26}, // interleave 3 x 64i8 into 96i8 (and store)
5184 
5185       {4, MVT::v8i8, 10},  // interleave 4 x 8i8  into 32i8  (and store)
5186       {4, MVT::v16i8, 11}, // interleave 4 x 16i8 into 64i8  (and store)
5187       {4, MVT::v32i8, 14}, // interleave 4 x 32i8 into 128i8 (and store)
5188       {4, MVT::v64i8, 24}  // interleave 4 x 32i8 into 256i8 (and store)
5189   };
5190 
5191   if (const auto *Entry =
5192           CostTableLookup(AVX512InterleavedStoreTbl, Factor, VT))
5193     return NumOfMemOps * MemOpCost + Entry->Cost;
5194   //If an entry does not exist, fallback to the default implementation.
5195 
5196   // There is no strided stores meanwhile. And store can't be folded in
5197   // shuffle.
5198   unsigned NumOfSources = Factor; // The number of values to be merged.
5199   InstructionCost ShuffleCost =
5200       getShuffleCost(TTI::SK_PermuteTwoSrc, SingleMemOpTy, None, 0, nullptr);
5201   unsigned NumOfShufflesPerStore = NumOfSources - 1;
5202 
5203   // The SK_MergeTwoSrc shuffle clobbers one of src operands.
5204   // We need additional instructions to keep sources.
5205   unsigned NumOfMoves = NumOfMemOps * NumOfShufflesPerStore / 2;
5206   InstructionCost Cost =
5207       NumOfMemOps * (MemOpCost + NumOfShufflesPerStore * ShuffleCost) +
5208       NumOfMoves;
5209   return Cost;
5210 }
5211 
5212 InstructionCost X86TTIImpl::getInterleavedMemoryOpCost(
5213     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
5214     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
5215     bool UseMaskForCond, bool UseMaskForGaps) {
5216   auto isSupportedOnAVX512 = [&](Type *VecTy, bool HasBW) {
5217     Type *EltTy = cast<VectorType>(VecTy)->getElementType();
5218     if (EltTy->isFloatTy() || EltTy->isDoubleTy() || EltTy->isIntegerTy(64) ||
5219         EltTy->isIntegerTy(32) || EltTy->isPointerTy())
5220       return true;
5221     if (EltTy->isIntegerTy(16) || EltTy->isIntegerTy(8) ||
5222         (!ST->useSoftFloat() && ST->hasFP16() && EltTy->isHalfTy()))
5223       return HasBW;
5224     return false;
5225   };
5226   if (ST->hasAVX512() && isSupportedOnAVX512(VecTy, ST->hasBWI()))
5227     return getInterleavedMemoryOpCostAVX512(
5228         Opcode, cast<FixedVectorType>(VecTy), Factor, Indices, Alignment,
5229         AddressSpace, CostKind, UseMaskForCond, UseMaskForGaps);
5230   if (ST->hasAVX2())
5231     return getInterleavedMemoryOpCostAVX2(
5232         Opcode, cast<FixedVectorType>(VecTy), Factor, Indices, Alignment,
5233         AddressSpace, CostKind, UseMaskForCond, UseMaskForGaps);
5234 
5235   return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
5236                                            Alignment, AddressSpace, CostKind,
5237                                            UseMaskForCond, UseMaskForGaps);
5238 }
5239