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     // UREM
263     return getArithmeticInstrCost(Instruction::And, Ty, CostKind, Op1Info,
264                                   Op2Info, TargetTransformInfo::OP_None,
265                                   TargetTransformInfo::OP_None);
266   }
267 
268   static const CostTblEntry GLMCostTable[] = {
269     { ISD::FDIV,  MVT::f32,   18 }, // divss
270     { ISD::FDIV,  MVT::v4f32, 35 }, // divps
271     { ISD::FDIV,  MVT::f64,   33 }, // divsd
272     { ISD::FDIV,  MVT::v2f64, 65 }, // divpd
273   };
274 
275   if (ST->useGLMDivSqrtCosts())
276     if (const auto *Entry = CostTableLookup(GLMCostTable, ISD,
277                                             LT.second))
278       return LT.first * Entry->Cost;
279 
280   static const CostTblEntry SLMCostTable[] = {
281     { ISD::MUL,   MVT::v4i32, 11 }, // pmulld
282     { ISD::MUL,   MVT::v8i16, 2  }, // pmullw
283     { ISD::FMUL,  MVT::f64,   2  }, // mulsd
284     { ISD::FMUL,  MVT::v2f64, 4  }, // mulpd
285     { ISD::FMUL,  MVT::v4f32, 2  }, // mulps
286     { ISD::FDIV,  MVT::f32,   17 }, // divss
287     { ISD::FDIV,  MVT::v4f32, 39 }, // divps
288     { ISD::FDIV,  MVT::f64,   32 }, // divsd
289     { ISD::FDIV,  MVT::v2f64, 69 }, // divpd
290     { ISD::FADD,  MVT::v2f64, 2  }, // addpd
291     { ISD::FSUB,  MVT::v2f64, 2  }, // subpd
292     // v2i64/v4i64 mul is custom lowered as a series of long:
293     // multiplies(3), shifts(3) and adds(2)
294     // slm muldq version throughput is 2 and addq throughput 4
295     // thus: 3X2 (muldq throughput) + 3X1 (shift throughput) +
296     //       3X4 (addq throughput) = 17
297     { ISD::MUL,   MVT::v2i64, 17 },
298     // slm addq\subq throughput is 4
299     { ISD::ADD,   MVT::v2i64, 4  },
300     { ISD::SUB,   MVT::v2i64, 4  },
301   };
302 
303   if (ST->isSLM()) {
304     if (Args.size() == 2 && ISD == ISD::MUL && LT.second == MVT::v4i32) {
305       // Check if the operands can be shrinked into a smaller datatype.
306       // TODO: Merge this into generiic vXi32 MUL patterns above.
307       bool Op1Signed = false;
308       unsigned Op1MinSize = BaseT::minRequiredElementSize(Args[0], Op1Signed);
309       bool Op2Signed = false;
310       unsigned Op2MinSize = BaseT::minRequiredElementSize(Args[1], Op2Signed);
311 
312       bool SignedMode = Op1Signed || Op2Signed;
313       unsigned OpMinSize = std::max(Op1MinSize, Op2MinSize);
314 
315       if (OpMinSize <= 7)
316         return LT.first * 3; // pmullw/sext
317       if (!SignedMode && OpMinSize <= 8)
318         return LT.first * 3; // pmullw/zext
319       if (OpMinSize <= 15)
320         return LT.first * 5; // pmullw/pmulhw/pshuf
321       if (!SignedMode && OpMinSize <= 16)
322         return LT.first * 5; // pmullw/pmulhw/pshuf
323     }
324 
325     if (const auto *Entry = CostTableLookup(SLMCostTable, ISD,
326                                             LT.second)) {
327       return LT.first * Entry->Cost;
328     }
329   }
330 
331   static const CostTblEntry AVX512BWUniformConstCostTable[] = {
332     { ISD::SHL,  MVT::v64i8,   2 }, // psllw + pand.
333     { ISD::SRL,  MVT::v64i8,   2 }, // psrlw + pand.
334     { ISD::SRA,  MVT::v64i8,   4 }, // psrlw, pand, pxor, psubb.
335   };
336 
337   if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
338       ST->hasBWI()) {
339     if (const auto *Entry = CostTableLookup(AVX512BWUniformConstCostTable, ISD,
340                                             LT.second))
341       return LT.first * Entry->Cost;
342   }
343 
344   static const CostTblEntry AVX512UniformConstCostTable[] = {
345     { ISD::SRA,  MVT::v2i64,   1 },
346     { ISD::SRA,  MVT::v4i64,   1 },
347     { ISD::SRA,  MVT::v8i64,   1 },
348 
349     { ISD::SHL,  MVT::v64i8,   4 }, // psllw + pand.
350     { ISD::SRL,  MVT::v64i8,   4 }, // psrlw + pand.
351     { ISD::SRA,  MVT::v64i8,   8 }, // psrlw, pand, pxor, psubb.
352 
353     { ISD::SDIV, MVT::v16i32,  6 }, // pmuludq sequence
354     { ISD::SREM, MVT::v16i32,  8 }, // pmuludq+mul+sub sequence
355     { ISD::UDIV, MVT::v16i32,  5 }, // pmuludq sequence
356     { ISD::UREM, MVT::v16i32,  7 }, // pmuludq+mul+sub sequence
357   };
358 
359   if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
360       ST->hasAVX512()) {
361     if (const auto *Entry = CostTableLookup(AVX512UniformConstCostTable, ISD,
362                                             LT.second))
363       return LT.first * Entry->Cost;
364   }
365 
366   static const CostTblEntry AVX2UniformConstCostTable[] = {
367     { ISD::SHL,  MVT::v32i8,   2 }, // psllw + pand.
368     { ISD::SRL,  MVT::v32i8,   2 }, // psrlw + pand.
369     { ISD::SRA,  MVT::v32i8,   4 }, // psrlw, pand, pxor, psubb.
370 
371     { ISD::SRA,  MVT::v4i64,   4 }, // 2 x psrad + shuffle.
372 
373     { ISD::SDIV, MVT::v8i32,   6 }, // pmuludq sequence
374     { ISD::SREM, MVT::v8i32,   8 }, // pmuludq+mul+sub sequence
375     { ISD::UDIV, MVT::v8i32,   5 }, // pmuludq sequence
376     { ISD::UREM, MVT::v8i32,   7 }, // pmuludq+mul+sub sequence
377   };
378 
379   if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
380       ST->hasAVX2()) {
381     if (const auto *Entry = CostTableLookup(AVX2UniformConstCostTable, ISD,
382                                             LT.second))
383       return LT.first * Entry->Cost;
384   }
385 
386   static const CostTblEntry SSE2UniformConstCostTable[] = {
387     { ISD::SHL,  MVT::v16i8,     2 }, // psllw + pand.
388     { ISD::SRL,  MVT::v16i8,     2 }, // psrlw + pand.
389     { ISD::SRA,  MVT::v16i8,     4 }, // psrlw, pand, pxor, psubb.
390 
391     { ISD::SHL,  MVT::v32i8,   4+2 }, // 2*(psllw + pand) + split.
392     { ISD::SRL,  MVT::v32i8,   4+2 }, // 2*(psrlw + pand) + split.
393     { ISD::SRA,  MVT::v32i8,   8+2 }, // 2*(psrlw, pand, pxor, psubb) + split.
394 
395     { ISD::SDIV, MVT::v8i32,  12+2 }, // 2*pmuludq sequence + split.
396     { ISD::SREM, MVT::v8i32,  16+2 }, // 2*pmuludq+mul+sub sequence + split.
397     { ISD::SDIV, MVT::v4i32,     6 }, // pmuludq sequence
398     { ISD::SREM, MVT::v4i32,     8 }, // pmuludq+mul+sub sequence
399     { ISD::UDIV, MVT::v8i32,  10+2 }, // 2*pmuludq sequence + split.
400     { ISD::UREM, MVT::v8i32,  14+2 }, // 2*pmuludq+mul+sub sequence + split.
401     { ISD::UDIV, MVT::v4i32,     5 }, // pmuludq sequence
402     { ISD::UREM, MVT::v4i32,     7 }, // pmuludq+mul+sub sequence
403   };
404 
405   // XOP has faster vXi8 shifts.
406   if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
407       ST->hasSSE2() && !ST->hasXOP()) {
408     if (const auto *Entry =
409             CostTableLookup(SSE2UniformConstCostTable, ISD, LT.second))
410       return LT.first * Entry->Cost;
411   }
412 
413   static const CostTblEntry AVX512BWConstCostTable[] = {
414     { ISD::SDIV, MVT::v64i8,  14 }, // 2*ext+2*pmulhw sequence
415     { ISD::SREM, MVT::v64i8,  16 }, // 2*ext+2*pmulhw+mul+sub sequence
416     { ISD::UDIV, MVT::v64i8,  14 }, // 2*ext+2*pmulhw sequence
417     { ISD::UREM, MVT::v64i8,  16 }, // 2*ext+2*pmulhw+mul+sub sequence
418     { ISD::SDIV, MVT::v32i16,  6 }, // vpmulhw sequence
419     { ISD::SREM, MVT::v32i16,  8 }, // vpmulhw+mul+sub sequence
420     { ISD::UDIV, MVT::v32i16,  6 }, // vpmulhuw sequence
421     { ISD::UREM, MVT::v32i16,  8 }, // vpmulhuw+mul+sub sequence
422   };
423 
424   if ((Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
425        Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) &&
426       ST->hasBWI()) {
427     if (const auto *Entry =
428             CostTableLookup(AVX512BWConstCostTable, ISD, LT.second))
429       return LT.first * Entry->Cost;
430   }
431 
432   static const CostTblEntry AVX512ConstCostTable[] = {
433     { ISD::SDIV, MVT::v16i32, 15 }, // vpmuldq sequence
434     { ISD::SREM, MVT::v16i32, 17 }, // vpmuldq+mul+sub sequence
435     { ISD::UDIV, MVT::v16i32, 15 }, // vpmuludq sequence
436     { ISD::UREM, MVT::v16i32, 17 }, // vpmuludq+mul+sub sequence
437     { ISD::SDIV, MVT::v64i8,  28 }, // 4*ext+4*pmulhw sequence
438     { ISD::SREM, MVT::v64i8,  32 }, // 4*ext+4*pmulhw+mul+sub sequence
439     { ISD::UDIV, MVT::v64i8,  28 }, // 4*ext+4*pmulhw sequence
440     { ISD::UREM, MVT::v64i8,  32 }, // 4*ext+4*pmulhw+mul+sub sequence
441     { ISD::SDIV, MVT::v32i16, 12 }, // 2*vpmulhw sequence
442     { ISD::SREM, MVT::v32i16, 16 }, // 2*vpmulhw+mul+sub sequence
443     { ISD::UDIV, MVT::v32i16, 12 }, // 2*vpmulhuw sequence
444     { ISD::UREM, MVT::v32i16, 16 }, // 2*vpmulhuw+mul+sub sequence
445   };
446 
447   if ((Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
448        Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) &&
449       ST->hasAVX512()) {
450     if (const auto *Entry =
451             CostTableLookup(AVX512ConstCostTable, ISD, LT.second))
452       return LT.first * Entry->Cost;
453   }
454 
455   static const CostTblEntry AVX2ConstCostTable[] = {
456     { ISD::SDIV, MVT::v32i8,  14 }, // 2*ext+2*pmulhw sequence
457     { ISD::SREM, MVT::v32i8,  16 }, // 2*ext+2*pmulhw+mul+sub sequence
458     { ISD::UDIV, MVT::v32i8,  14 }, // 2*ext+2*pmulhw sequence
459     { ISD::UREM, MVT::v32i8,  16 }, // 2*ext+2*pmulhw+mul+sub sequence
460     { ISD::SDIV, MVT::v16i16,  6 }, // vpmulhw sequence
461     { ISD::SREM, MVT::v16i16,  8 }, // vpmulhw+mul+sub sequence
462     { ISD::UDIV, MVT::v16i16,  6 }, // vpmulhuw sequence
463     { ISD::UREM, MVT::v16i16,  8 }, // vpmulhuw+mul+sub sequence
464     { ISD::SDIV, MVT::v8i32,  15 }, // vpmuldq sequence
465     { ISD::SREM, MVT::v8i32,  19 }, // vpmuldq+mul+sub sequence
466     { ISD::UDIV, MVT::v8i32,  15 }, // vpmuludq sequence
467     { ISD::UREM, MVT::v8i32,  19 }, // vpmuludq+mul+sub sequence
468   };
469 
470   if ((Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
471        Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) &&
472       ST->hasAVX2()) {
473     if (const auto *Entry = CostTableLookup(AVX2ConstCostTable, ISD, LT.second))
474       return LT.first * Entry->Cost;
475   }
476 
477   static const CostTblEntry SSE2ConstCostTable[] = {
478     { ISD::SDIV, MVT::v32i8,  28+2 }, // 4*ext+4*pmulhw sequence + split.
479     { ISD::SREM, MVT::v32i8,  32+2 }, // 4*ext+4*pmulhw+mul+sub sequence + split.
480     { ISD::SDIV, MVT::v16i8,    14 }, // 2*ext+2*pmulhw sequence
481     { ISD::SREM, MVT::v16i8,    16 }, // 2*ext+2*pmulhw+mul+sub sequence
482     { ISD::UDIV, MVT::v32i8,  28+2 }, // 4*ext+4*pmulhw sequence + split.
483     { ISD::UREM, MVT::v32i8,  32+2 }, // 4*ext+4*pmulhw+mul+sub sequence + split.
484     { ISD::UDIV, MVT::v16i8,    14 }, // 2*ext+2*pmulhw sequence
485     { ISD::UREM, MVT::v16i8,    16 }, // 2*ext+2*pmulhw+mul+sub sequence
486     { ISD::SDIV, MVT::v16i16, 12+2 }, // 2*pmulhw sequence + split.
487     { ISD::SREM, MVT::v16i16, 16+2 }, // 2*pmulhw+mul+sub sequence + split.
488     { ISD::SDIV, MVT::v8i16,     6 }, // pmulhw sequence
489     { ISD::SREM, MVT::v8i16,     8 }, // pmulhw+mul+sub sequence
490     { ISD::UDIV, MVT::v16i16, 12+2 }, // 2*pmulhuw sequence + split.
491     { ISD::UREM, MVT::v16i16, 16+2 }, // 2*pmulhuw+mul+sub sequence + split.
492     { ISD::UDIV, MVT::v8i16,     6 }, // pmulhuw sequence
493     { ISD::UREM, MVT::v8i16,     8 }, // pmulhuw+mul+sub sequence
494     { ISD::SDIV, MVT::v8i32,  38+2 }, // 2*pmuludq sequence + split.
495     { ISD::SREM, MVT::v8i32,  48+2 }, // 2*pmuludq+mul+sub sequence + split.
496     { ISD::SDIV, MVT::v4i32,    19 }, // pmuludq sequence
497     { ISD::SREM, MVT::v4i32,    24 }, // pmuludq+mul+sub sequence
498     { ISD::UDIV, MVT::v8i32,  30+2 }, // 2*pmuludq sequence + split.
499     { ISD::UREM, MVT::v8i32,  40+2 }, // 2*pmuludq+mul+sub sequence + split.
500     { ISD::UDIV, MVT::v4i32,    15 }, // pmuludq sequence
501     { ISD::UREM, MVT::v4i32,    20 }, // pmuludq+mul+sub sequence
502   };
503 
504   if ((Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
505        Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) &&
506       ST->hasSSE2()) {
507     // pmuldq sequence.
508     if (ISD == ISD::SDIV && LT.second == MVT::v8i32 && ST->hasAVX())
509       return LT.first * 32;
510     if (ISD == ISD::SREM && LT.second == MVT::v8i32 && ST->hasAVX())
511       return LT.first * 38;
512     if (ISD == ISD::SDIV && LT.second == MVT::v4i32 && ST->hasSSE41())
513       return LT.first * 15;
514     if (ISD == ISD::SREM && LT.second == MVT::v4i32 && ST->hasSSE41())
515       return LT.first * 20;
516 
517     if (const auto *Entry = CostTableLookup(SSE2ConstCostTable, ISD, LT.second))
518       return LT.first * Entry->Cost;
519   }
520 
521   static const CostTblEntry AVX512BWShiftCostTable[] = {
522     { ISD::SHL,   MVT::v16i8,      4 }, // extend/vpsllvw/pack sequence.
523     { ISD::SRL,   MVT::v16i8,      4 }, // extend/vpsrlvw/pack sequence.
524     { ISD::SRA,   MVT::v16i8,      4 }, // extend/vpsravw/pack sequence.
525     { ISD::SHL,   MVT::v32i8,      4 }, // extend/vpsllvw/pack sequence.
526     { ISD::SRL,   MVT::v32i8,      4 }, // extend/vpsrlvw/pack sequence.
527     { ISD::SRA,   MVT::v32i8,      6 }, // extend/vpsravw/pack sequence.
528     { ISD::SHL,   MVT::v64i8,      6 }, // extend/vpsllvw/pack sequence.
529     { ISD::SRL,   MVT::v64i8,      7 }, // extend/vpsrlvw/pack sequence.
530     { ISD::SRA,   MVT::v64i8,     15 }, // extend/vpsravw/pack sequence.
531 
532     { ISD::SHL,   MVT::v8i16,      1 }, // vpsllvw
533     { ISD::SRL,   MVT::v8i16,      1 }, // vpsrlvw
534     { ISD::SRA,   MVT::v8i16,      1 }, // vpsravw
535     { ISD::SHL,   MVT::v16i16,     1 }, // vpsllvw
536     { ISD::SRL,   MVT::v16i16,     1 }, // vpsrlvw
537     { ISD::SRA,   MVT::v16i16,     1 }, // vpsravw
538     { ISD::SHL,   MVT::v32i16,     1 }, // vpsllvw
539     { ISD::SRL,   MVT::v32i16,     1 }, // vpsrlvw
540     { ISD::SRA,   MVT::v32i16,     1 }, // vpsravw
541   };
542 
543   if (ST->hasBWI())
544     if (const auto *Entry = CostTableLookup(AVX512BWShiftCostTable, ISD, LT.second))
545       return LT.first * Entry->Cost;
546 
547   static const CostTblEntry AVX2UniformCostTable[] = {
548     // Uniform splats are cheaper for the following instructions.
549     { ISD::SHL,  MVT::v16i16, 1 }, // psllw.
550     { ISD::SRL,  MVT::v16i16, 1 }, // psrlw.
551     { ISD::SRA,  MVT::v16i16, 1 }, // psraw.
552     { ISD::SHL,  MVT::v32i16, 2 }, // 2*psllw.
553     { ISD::SRL,  MVT::v32i16, 2 }, // 2*psrlw.
554     { ISD::SRA,  MVT::v32i16, 2 }, // 2*psraw.
555 
556     { ISD::SHL,  MVT::v8i32,  1 }, // pslld
557     { ISD::SRL,  MVT::v8i32,  1 }, // psrld
558     { ISD::SRA,  MVT::v8i32,  1 }, // psrad
559     { ISD::SHL,  MVT::v4i64,  1 }, // psllq
560     { ISD::SRL,  MVT::v4i64,  1 }, // psrlq
561   };
562 
563   if (ST->hasAVX2() &&
564       ((Op2Info == TargetTransformInfo::OK_UniformConstantValue) ||
565        (Op2Info == TargetTransformInfo::OK_UniformValue))) {
566     if (const auto *Entry =
567             CostTableLookup(AVX2UniformCostTable, ISD, LT.second))
568       return LT.first * Entry->Cost;
569   }
570 
571   static const CostTblEntry SSE2UniformCostTable[] = {
572     // Uniform splats are cheaper for the following instructions.
573     { ISD::SHL,  MVT::v8i16,  1 }, // psllw.
574     { ISD::SHL,  MVT::v4i32,  1 }, // pslld
575     { ISD::SHL,  MVT::v2i64,  1 }, // psllq.
576 
577     { ISD::SRL,  MVT::v8i16,  1 }, // psrlw.
578     { ISD::SRL,  MVT::v4i32,  1 }, // psrld.
579     { ISD::SRL,  MVT::v2i64,  1 }, // psrlq.
580 
581     { ISD::SRA,  MVT::v8i16,  1 }, // psraw.
582     { ISD::SRA,  MVT::v4i32,  1 }, // psrad.
583   };
584 
585   if (ST->hasSSE2() &&
586       ((Op2Info == TargetTransformInfo::OK_UniformConstantValue) ||
587        (Op2Info == TargetTransformInfo::OK_UniformValue))) {
588     if (const auto *Entry =
589             CostTableLookup(SSE2UniformCostTable, ISD, LT.second))
590       return LT.first * Entry->Cost;
591   }
592 
593   static const CostTblEntry AVX512DQCostTable[] = {
594     { ISD::MUL,  MVT::v2i64, 2 }, // pmullq
595     { ISD::MUL,  MVT::v4i64, 2 }, // pmullq
596     { ISD::MUL,  MVT::v8i64, 2 }  // pmullq
597   };
598 
599   // Look for AVX512DQ lowering tricks for custom cases.
600   if (ST->hasDQI())
601     if (const auto *Entry = CostTableLookup(AVX512DQCostTable, ISD, LT.second))
602       return LT.first * Entry->Cost;
603 
604   static const CostTblEntry AVX512BWCostTable[] = {
605     { ISD::SHL,   MVT::v64i8,     11 }, // vpblendvb sequence.
606     { ISD::SRL,   MVT::v64i8,     11 }, // vpblendvb sequence.
607     { ISD::SRA,   MVT::v64i8,     24 }, // vpblendvb sequence.
608   };
609 
610   // Look for AVX512BW lowering tricks for custom cases.
611   if (ST->hasBWI())
612     if (const auto *Entry = CostTableLookup(AVX512BWCostTable, ISD, LT.second))
613       return LT.first * Entry->Cost;
614 
615   static const CostTblEntry AVX512CostTable[] = {
616     { ISD::SHL,     MVT::v4i32,      1 },
617     { ISD::SRL,     MVT::v4i32,      1 },
618     { ISD::SRA,     MVT::v4i32,      1 },
619     { ISD::SHL,     MVT::v8i32,      1 },
620     { ISD::SRL,     MVT::v8i32,      1 },
621     { ISD::SRA,     MVT::v8i32,      1 },
622     { ISD::SHL,     MVT::v16i32,     1 },
623     { ISD::SRL,     MVT::v16i32,     1 },
624     { ISD::SRA,     MVT::v16i32,     1 },
625 
626     { ISD::SHL,     MVT::v2i64,      1 },
627     { ISD::SRL,     MVT::v2i64,      1 },
628     { ISD::SHL,     MVT::v4i64,      1 },
629     { ISD::SRL,     MVT::v4i64,      1 },
630     { ISD::SHL,     MVT::v8i64,      1 },
631     { ISD::SRL,     MVT::v8i64,      1 },
632 
633     { ISD::SRA,     MVT::v2i64,      1 },
634     { ISD::SRA,     MVT::v4i64,      1 },
635     { ISD::SRA,     MVT::v8i64,      1 },
636 
637     { ISD::MUL,     MVT::v16i32,     1 }, // pmulld (Skylake from agner.org)
638     { ISD::MUL,     MVT::v8i32,      1 }, // pmulld (Skylake from agner.org)
639     { ISD::MUL,     MVT::v4i32,      1 }, // pmulld (Skylake from agner.org)
640     { ISD::MUL,     MVT::v8i64,      6 }, // 3*pmuludq/3*shift/2*add
641 
642     { ISD::FNEG,    MVT::v8f64,      1 }, // Skylake from http://www.agner.org/
643     { ISD::FADD,    MVT::v8f64,      1 }, // Skylake from http://www.agner.org/
644     { ISD::FSUB,    MVT::v8f64,      1 }, // Skylake from http://www.agner.org/
645     { ISD::FMUL,    MVT::v8f64,      1 }, // Skylake from http://www.agner.org/
646     { ISD::FDIV,    MVT::f64,        4 }, // Skylake from http://www.agner.org/
647     { ISD::FDIV,    MVT::v2f64,      4 }, // Skylake from http://www.agner.org/
648     { ISD::FDIV,    MVT::v4f64,      8 }, // Skylake from http://www.agner.org/
649     { ISD::FDIV,    MVT::v8f64,     16 }, // Skylake from http://www.agner.org/
650 
651     { ISD::FNEG,    MVT::v16f32,     1 }, // Skylake from http://www.agner.org/
652     { ISD::FADD,    MVT::v16f32,     1 }, // Skylake from http://www.agner.org/
653     { ISD::FSUB,    MVT::v16f32,     1 }, // Skylake from http://www.agner.org/
654     { ISD::FMUL,    MVT::v16f32,     1 }, // Skylake from http://www.agner.org/
655     { ISD::FDIV,    MVT::f32,        3 }, // Skylake from http://www.agner.org/
656     { ISD::FDIV,    MVT::v4f32,      3 }, // Skylake from http://www.agner.org/
657     { ISD::FDIV,    MVT::v8f32,      5 }, // Skylake from http://www.agner.org/
658     { ISD::FDIV,    MVT::v16f32,    10 }, // Skylake from http://www.agner.org/
659   };
660 
661   if (ST->hasAVX512())
662     if (const auto *Entry = CostTableLookup(AVX512CostTable, ISD, LT.second))
663       return LT.first * Entry->Cost;
664 
665   static const CostTblEntry AVX2ShiftCostTable[] = {
666     // Shifts on vXi64/vXi32 on AVX2 is legal even though we declare to
667     // customize them to detect the cases where shift amount is a scalar one.
668     { ISD::SHL,     MVT::v4i32,    2 }, // vpsllvd (Haswell from agner.org)
669     { ISD::SRL,     MVT::v4i32,    2 }, // vpsrlvd (Haswell from agner.org)
670     { ISD::SRA,     MVT::v4i32,    2 }, // vpsravd (Haswell from agner.org)
671     { ISD::SHL,     MVT::v8i32,    2 }, // vpsllvd (Haswell from agner.org)
672     { ISD::SRL,     MVT::v8i32,    2 }, // vpsrlvd (Haswell from agner.org)
673     { ISD::SRA,     MVT::v8i32,    2 }, // vpsravd (Haswell from agner.org)
674     { ISD::SHL,     MVT::v2i64,    1 }, // vpsllvq (Haswell from agner.org)
675     { ISD::SRL,     MVT::v2i64,    1 }, // vpsrlvq (Haswell from agner.org)
676     { ISD::SHL,     MVT::v4i64,    1 }, // vpsllvq (Haswell from agner.org)
677     { ISD::SRL,     MVT::v4i64,    1 }, // vpsrlvq (Haswell from agner.org)
678   };
679 
680   if (ST->hasAVX512()) {
681     if (ISD == ISD::SHL && LT.second == MVT::v32i16 &&
682         (Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
683          Op2Info == TargetTransformInfo::OK_NonUniformConstantValue))
684       // On AVX512, a packed v32i16 shift left by a constant build_vector
685       // is lowered into a vector multiply (vpmullw).
686       return getArithmeticInstrCost(Instruction::Mul, Ty, CostKind,
687                                     Op1Info, Op2Info,
688                                     TargetTransformInfo::OP_None,
689                                     TargetTransformInfo::OP_None);
690   }
691 
692   // Look for AVX2 lowering tricks (XOP is always better at v4i32 shifts).
693   if (ST->hasAVX2() && !(ST->hasXOP() && LT.second == MVT::v4i32)) {
694     if (ISD == ISD::SHL && LT.second == MVT::v16i16 &&
695         (Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
696          Op2Info == TargetTransformInfo::OK_NonUniformConstantValue))
697       // On AVX2, a packed v16i16 shift left by a constant build_vector
698       // is lowered into a vector multiply (vpmullw).
699       return getArithmeticInstrCost(Instruction::Mul, Ty, CostKind,
700                                     Op1Info, Op2Info,
701                                     TargetTransformInfo::OP_None,
702                                     TargetTransformInfo::OP_None);
703 
704     if (const auto *Entry = CostTableLookup(AVX2ShiftCostTable, ISD, LT.second))
705       return LT.first * Entry->Cost;
706   }
707 
708   static const CostTblEntry XOPShiftCostTable[] = {
709     // 128bit shifts take 1cy, but right shifts require negation beforehand.
710     { ISD::SHL,     MVT::v16i8,    1 },
711     { ISD::SRL,     MVT::v16i8,    2 },
712     { ISD::SRA,     MVT::v16i8,    2 },
713     { ISD::SHL,     MVT::v8i16,    1 },
714     { ISD::SRL,     MVT::v8i16,    2 },
715     { ISD::SRA,     MVT::v8i16,    2 },
716     { ISD::SHL,     MVT::v4i32,    1 },
717     { ISD::SRL,     MVT::v4i32,    2 },
718     { ISD::SRA,     MVT::v4i32,    2 },
719     { ISD::SHL,     MVT::v2i64,    1 },
720     { ISD::SRL,     MVT::v2i64,    2 },
721     { ISD::SRA,     MVT::v2i64,    2 },
722     // 256bit shifts require splitting if AVX2 didn't catch them above.
723     { ISD::SHL,     MVT::v32i8,  2+2 },
724     { ISD::SRL,     MVT::v32i8,  4+2 },
725     { ISD::SRA,     MVT::v32i8,  4+2 },
726     { ISD::SHL,     MVT::v16i16, 2+2 },
727     { ISD::SRL,     MVT::v16i16, 4+2 },
728     { ISD::SRA,     MVT::v16i16, 4+2 },
729     { ISD::SHL,     MVT::v8i32,  2+2 },
730     { ISD::SRL,     MVT::v8i32,  4+2 },
731     { ISD::SRA,     MVT::v8i32,  4+2 },
732     { ISD::SHL,     MVT::v4i64,  2+2 },
733     { ISD::SRL,     MVT::v4i64,  4+2 },
734     { ISD::SRA,     MVT::v4i64,  4+2 },
735   };
736 
737   // Look for XOP lowering tricks.
738   if (ST->hasXOP()) {
739     // If the right shift is constant then we'll fold the negation so
740     // it's as cheap as a left shift.
741     int ShiftISD = ISD;
742     if ((ShiftISD == ISD::SRL || ShiftISD == ISD::SRA) &&
743         (Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
744          Op2Info == TargetTransformInfo::OK_NonUniformConstantValue))
745       ShiftISD = ISD::SHL;
746     if (const auto *Entry =
747             CostTableLookup(XOPShiftCostTable, ShiftISD, LT.second))
748       return LT.first * Entry->Cost;
749   }
750 
751   static const CostTblEntry SSE2UniformShiftCostTable[] = {
752     // Uniform splats are cheaper for the following instructions.
753     { ISD::SHL,  MVT::v16i16, 2+2 }, // 2*psllw + split.
754     { ISD::SHL,  MVT::v8i32,  2+2 }, // 2*pslld + split.
755     { ISD::SHL,  MVT::v4i64,  2+2 }, // 2*psllq + split.
756 
757     { ISD::SRL,  MVT::v16i16, 2+2 }, // 2*psrlw + split.
758     { ISD::SRL,  MVT::v8i32,  2+2 }, // 2*psrld + split.
759     { ISD::SRL,  MVT::v4i64,  2+2 }, // 2*psrlq + split.
760 
761     { ISD::SRA,  MVT::v16i16, 2+2 }, // 2*psraw + split.
762     { ISD::SRA,  MVT::v8i32,  2+2 }, // 2*psrad + split.
763     { ISD::SRA,  MVT::v2i64,    4 }, // 2*psrad + shuffle.
764     { ISD::SRA,  MVT::v4i64,  8+2 }, // 2*(2*psrad + shuffle) + split.
765   };
766 
767   if (ST->hasSSE2() &&
768       ((Op2Info == TargetTransformInfo::OK_UniformConstantValue) ||
769        (Op2Info == TargetTransformInfo::OK_UniformValue))) {
770 
771     // Handle AVX2 uniform v4i64 ISD::SRA, it's not worth a table.
772     if (ISD == ISD::SRA && LT.second == MVT::v4i64 && ST->hasAVX2())
773       return LT.first * 4; // 2*psrad + shuffle.
774 
775     if (const auto *Entry =
776             CostTableLookup(SSE2UniformShiftCostTable, ISD, LT.second))
777       return LT.first * Entry->Cost;
778   }
779 
780   if (ISD == ISD::SHL &&
781       Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) {
782     MVT VT = LT.second;
783     // Vector shift left by non uniform constant can be lowered
784     // into vector multiply.
785     if (((VT == MVT::v8i16 || VT == MVT::v4i32) && ST->hasSSE2()) ||
786         ((VT == MVT::v16i16 || VT == MVT::v8i32) && ST->hasAVX()))
787       ISD = ISD::MUL;
788   }
789 
790   static const CostTblEntry AVX2CostTable[] = {
791     { ISD::SHL,  MVT::v16i8,      6 }, // vpblendvb sequence.
792     { ISD::SHL,  MVT::v32i8,      6 }, // vpblendvb sequence.
793     { ISD::SHL,  MVT::v64i8,     12 }, // 2*vpblendvb sequence.
794     { ISD::SHL,  MVT::v8i16,      5 }, // extend/vpsrlvd/pack sequence.
795     { ISD::SHL,  MVT::v16i16,     7 }, // extend/vpsrlvd/pack sequence.
796     { ISD::SHL,  MVT::v32i16,    14 }, // 2*extend/vpsrlvd/pack sequence.
797 
798     { ISD::SRL,  MVT::v16i8,      6 }, // vpblendvb sequence.
799     { ISD::SRL,  MVT::v32i8,      6 }, // vpblendvb sequence.
800     { ISD::SRL,  MVT::v64i8,     12 }, // 2*vpblendvb sequence.
801     { ISD::SRL,  MVT::v8i16,      5 }, // extend/vpsrlvd/pack sequence.
802     { ISD::SRL,  MVT::v16i16,     7 }, // extend/vpsrlvd/pack sequence.
803     { ISD::SRL,  MVT::v32i16,    14 }, // 2*extend/vpsrlvd/pack sequence.
804 
805     { ISD::SRA,  MVT::v16i8,     17 }, // vpblendvb sequence.
806     { ISD::SRA,  MVT::v32i8,     17 }, // vpblendvb sequence.
807     { ISD::SRA,  MVT::v64i8,     34 }, // 2*vpblendvb sequence.
808     { ISD::SRA,  MVT::v8i16,      5 }, // extend/vpsravd/pack sequence.
809     { ISD::SRA,  MVT::v16i16,     7 }, // extend/vpsravd/pack sequence.
810     { ISD::SRA,  MVT::v32i16,    14 }, // 2*extend/vpsravd/pack sequence.
811     { ISD::SRA,  MVT::v2i64,      2 }, // srl/xor/sub sequence.
812     { ISD::SRA,  MVT::v4i64,      2 }, // srl/xor/sub sequence.
813 
814     { ISD::SUB,  MVT::v32i8,      1 }, // psubb
815     { ISD::ADD,  MVT::v32i8,      1 }, // paddb
816     { ISD::SUB,  MVT::v16i16,     1 }, // psubw
817     { ISD::ADD,  MVT::v16i16,     1 }, // paddw
818     { ISD::SUB,  MVT::v8i32,      1 }, // psubd
819     { ISD::ADD,  MVT::v8i32,      1 }, // paddd
820     { ISD::SUB,  MVT::v4i64,      1 }, // psubq
821     { ISD::ADD,  MVT::v4i64,      1 }, // paddq
822 
823     { ISD::MUL,  MVT::v16i16,     1 }, // pmullw
824     { ISD::MUL,  MVT::v8i32,      2 }, // pmulld (Haswell from agner.org)
825     { ISD::MUL,  MVT::v4i64,      6 }, // 3*pmuludq/3*shift/2*add
826 
827     { ISD::FNEG, MVT::v4f64,      1 }, // Haswell from http://www.agner.org/
828     { ISD::FNEG, MVT::v8f32,      1 }, // Haswell from http://www.agner.org/
829     { ISD::FADD, MVT::v4f64,      1 }, // Haswell from http://www.agner.org/
830     { ISD::FADD, MVT::v8f32,      1 }, // Haswell from http://www.agner.org/
831     { ISD::FSUB, MVT::v4f64,      1 }, // Haswell from http://www.agner.org/
832     { ISD::FSUB, MVT::v8f32,      1 }, // Haswell from http://www.agner.org/
833     { ISD::FMUL, MVT::f64,        1 }, // Haswell from http://www.agner.org/
834     { ISD::FMUL, MVT::v2f64,      1 }, // Haswell from http://www.agner.org/
835     { ISD::FMUL, MVT::v4f64,      1 }, // Haswell from http://www.agner.org/
836     { ISD::FMUL, MVT::v8f32,      1 }, // Haswell from http://www.agner.org/
837 
838     { ISD::FDIV, MVT::f32,        7 }, // Haswell from http://www.agner.org/
839     { ISD::FDIV, MVT::v4f32,      7 }, // Haswell from http://www.agner.org/
840     { ISD::FDIV, MVT::v8f32,     14 }, // Haswell from http://www.agner.org/
841     { ISD::FDIV, MVT::f64,       14 }, // Haswell from http://www.agner.org/
842     { ISD::FDIV, MVT::v2f64,     14 }, // Haswell from http://www.agner.org/
843     { ISD::FDIV, MVT::v4f64,     28 }, // Haswell from http://www.agner.org/
844   };
845 
846   // Look for AVX2 lowering tricks for custom cases.
847   if (ST->hasAVX2())
848     if (const auto *Entry = CostTableLookup(AVX2CostTable, ISD, LT.second))
849       return LT.first * Entry->Cost;
850 
851   static const CostTblEntry AVX1CostTable[] = {
852     // We don't have to scalarize unsupported ops. We can issue two half-sized
853     // operations and we only need to extract the upper YMM half.
854     // Two ops + 1 extract + 1 insert = 4.
855     { ISD::MUL,     MVT::v16i16,     4 },
856     { ISD::MUL,     MVT::v8i32,      5 }, // BTVER2 from http://www.agner.org/
857     { ISD::MUL,     MVT::v4i64,     12 },
858 
859     { ISD::SUB,     MVT::v32i8,      4 },
860     { ISD::ADD,     MVT::v32i8,      4 },
861     { ISD::SUB,     MVT::v16i16,     4 },
862     { ISD::ADD,     MVT::v16i16,     4 },
863     { ISD::SUB,     MVT::v8i32,      4 },
864     { ISD::ADD,     MVT::v8i32,      4 },
865     { ISD::SUB,     MVT::v4i64,      4 },
866     { ISD::ADD,     MVT::v4i64,      4 },
867 
868     { ISD::SHL,     MVT::v32i8,     22 }, // pblendvb sequence + split.
869     { ISD::SHL,     MVT::v8i16,      6 }, // pblendvb sequence.
870     { ISD::SHL,     MVT::v16i16,    13 }, // pblendvb sequence + split.
871     { ISD::SHL,     MVT::v4i32,      3 }, // pslld/paddd/cvttps2dq/pmulld
872     { ISD::SHL,     MVT::v8i32,      9 }, // pslld/paddd/cvttps2dq/pmulld + split
873     { ISD::SHL,     MVT::v2i64,      2 }, // Shift each lane + blend.
874     { ISD::SHL,     MVT::v4i64,      6 }, // Shift each lane + blend + split.
875 
876     { ISD::SRL,     MVT::v32i8,     23 }, // pblendvb sequence + split.
877     { ISD::SRL,     MVT::v16i16,    28 }, // pblendvb sequence + split.
878     { ISD::SRL,     MVT::v4i32,      6 }, // Shift each lane + blend.
879     { ISD::SRL,     MVT::v8i32,     14 }, // Shift each lane + blend + split.
880     { ISD::SRL,     MVT::v2i64,      2 }, // Shift each lane + blend.
881     { ISD::SRL,     MVT::v4i64,      6 }, // Shift each lane + blend + split.
882 
883     { ISD::SRA,     MVT::v32i8,     44 }, // pblendvb sequence + split.
884     { ISD::SRA,     MVT::v16i16,    28 }, // pblendvb sequence + split.
885     { ISD::SRA,     MVT::v4i32,      6 }, // Shift each lane + blend.
886     { ISD::SRA,     MVT::v8i32,     14 }, // Shift each lane + blend + split.
887     { ISD::SRA,     MVT::v2i64,      5 }, // Shift each lane + blend.
888     { ISD::SRA,     MVT::v4i64,     12 }, // Shift each lane + blend + split.
889 
890     { ISD::FNEG,    MVT::v4f64,      2 }, // BTVER2 from http://www.agner.org/
891     { ISD::FNEG,    MVT::v8f32,      2 }, // BTVER2 from http://www.agner.org/
892 
893     { ISD::FMUL,    MVT::f64,        2 }, // BTVER2 from http://www.agner.org/
894     { ISD::FMUL,    MVT::v2f64,      2 }, // BTVER2 from http://www.agner.org/
895     { ISD::FMUL,    MVT::v4f64,      4 }, // BTVER2 from http://www.agner.org/
896 
897     { ISD::FDIV,    MVT::f32,       14 }, // SNB from http://www.agner.org/
898     { ISD::FDIV,    MVT::v4f32,     14 }, // SNB from http://www.agner.org/
899     { ISD::FDIV,    MVT::v8f32,     28 }, // SNB from http://www.agner.org/
900     { ISD::FDIV,    MVT::f64,       22 }, // SNB from http://www.agner.org/
901     { ISD::FDIV,    MVT::v2f64,     22 }, // SNB from http://www.agner.org/
902     { ISD::FDIV,    MVT::v4f64,     44 }, // SNB from http://www.agner.org/
903   };
904 
905   if (ST->hasAVX())
906     if (const auto *Entry = CostTableLookup(AVX1CostTable, ISD, LT.second))
907       return LT.first * Entry->Cost;
908 
909   static const CostTblEntry SSE42CostTable[] = {
910     { ISD::FADD, MVT::f64,     1 }, // Nehalem from http://www.agner.org/
911     { ISD::FADD, MVT::f32,     1 }, // Nehalem from http://www.agner.org/
912     { ISD::FADD, MVT::v2f64,   1 }, // Nehalem from http://www.agner.org/
913     { ISD::FADD, MVT::v4f32,   1 }, // Nehalem from http://www.agner.org/
914 
915     { ISD::FSUB, MVT::f64,     1 }, // Nehalem from http://www.agner.org/
916     { ISD::FSUB, MVT::f32 ,    1 }, // Nehalem from http://www.agner.org/
917     { ISD::FSUB, MVT::v2f64,   1 }, // Nehalem from http://www.agner.org/
918     { ISD::FSUB, MVT::v4f32,   1 }, // Nehalem from http://www.agner.org/
919 
920     { ISD::FMUL, MVT::f64,     1 }, // Nehalem from http://www.agner.org/
921     { ISD::FMUL, MVT::f32,     1 }, // Nehalem from http://www.agner.org/
922     { ISD::FMUL, MVT::v2f64,   1 }, // Nehalem from http://www.agner.org/
923     { ISD::FMUL, MVT::v4f32,   1 }, // Nehalem from http://www.agner.org/
924 
925     { ISD::FDIV,  MVT::f32,   14 }, // Nehalem from http://www.agner.org/
926     { ISD::FDIV,  MVT::v4f32, 14 }, // Nehalem from http://www.agner.org/
927     { ISD::FDIV,  MVT::f64,   22 }, // Nehalem from http://www.agner.org/
928     { ISD::FDIV,  MVT::v2f64, 22 }, // Nehalem from http://www.agner.org/
929 
930     { ISD::MUL,   MVT::v2i64,  6 }  // 3*pmuludq/3*shift/2*add
931   };
932 
933   if (ST->hasSSE42())
934     if (const auto *Entry = CostTableLookup(SSE42CostTable, ISD, LT.second))
935       return LT.first * Entry->Cost;
936 
937   static const CostTblEntry SSE41CostTable[] = {
938     { ISD::SHL,  MVT::v16i8,      10 }, // pblendvb sequence.
939     { ISD::SHL,  MVT::v8i16,      11 }, // pblendvb sequence.
940     { ISD::SHL,  MVT::v4i32,       4 }, // pslld/paddd/cvttps2dq/pmulld
941 
942     { ISD::SRL,  MVT::v16i8,      11 }, // pblendvb sequence.
943     { ISD::SRL,  MVT::v8i16,      13 }, // pblendvb sequence.
944     { ISD::SRL,  MVT::v4i32,      16 }, // Shift each lane + blend.
945 
946     { ISD::SRA,  MVT::v16i8,      21 }, // pblendvb sequence.
947     { ISD::SRA,  MVT::v8i16,      13 }, // pblendvb sequence.
948 
949     { ISD::MUL,  MVT::v4i32,       2 }  // pmulld (Nehalem from agner.org)
950   };
951 
952   if (ST->hasSSE41())
953     if (const auto *Entry = CostTableLookup(SSE41CostTable, ISD, LT.second))
954       return LT.first * Entry->Cost;
955 
956   static const CostTblEntry SSE2CostTable[] = {
957     // We don't correctly identify costs of casts because they are marked as
958     // custom.
959     { ISD::SHL,  MVT::v16i8,      13 }, // cmpgtb sequence.
960     { ISD::SHL,  MVT::v8i16,      25 }, // cmpgtw sequence.
961     { ISD::SHL,  MVT::v4i32,      16 }, // pslld/paddd/cvttps2dq/pmuludq.
962     { ISD::SHL,  MVT::v2i64,       4 }, // splat+shuffle sequence.
963 
964     { ISD::SRL,  MVT::v16i8,      14 }, // cmpgtb sequence.
965     { ISD::SRL,  MVT::v8i16,      16 }, // cmpgtw sequence.
966     { ISD::SRL,  MVT::v4i32,      12 }, // Shift each lane + blend.
967     { ISD::SRL,  MVT::v2i64,       4 }, // splat+shuffle sequence.
968 
969     { ISD::SRA,  MVT::v16i8,      27 }, // unpacked cmpgtb sequence.
970     { ISD::SRA,  MVT::v8i16,      16 }, // cmpgtw sequence.
971     { ISD::SRA,  MVT::v4i32,      12 }, // Shift each lane + blend.
972     { ISD::SRA,  MVT::v2i64,       8 }, // srl/xor/sub splat+shuffle sequence.
973 
974     { ISD::MUL,  MVT::v8i16,       1 }, // pmullw
975     { ISD::MUL,  MVT::v4i32,       6 }, // 3*pmuludq/4*shuffle
976     { ISD::MUL,  MVT::v2i64,       8 }, // 3*pmuludq/3*shift/2*add
977 
978     { ISD::FDIV, MVT::f32,        23 }, // Pentium IV from http://www.agner.org/
979     { ISD::FDIV, MVT::v4f32,      39 }, // Pentium IV from http://www.agner.org/
980     { ISD::FDIV, MVT::f64,        38 }, // Pentium IV from http://www.agner.org/
981     { ISD::FDIV, MVT::v2f64,      69 }, // Pentium IV from http://www.agner.org/
982 
983     { ISD::FNEG, MVT::f32,         1 }, // Pentium IV from http://www.agner.org/
984     { ISD::FNEG, MVT::f64,         1 }, // Pentium IV from http://www.agner.org/
985     { ISD::FNEG, MVT::v4f32,       1 }, // Pentium IV from http://www.agner.org/
986     { ISD::FNEG, MVT::v2f64,       1 }, // Pentium IV from http://www.agner.org/
987 
988     { ISD::FADD, MVT::f32,         2 }, // Pentium IV from http://www.agner.org/
989     { ISD::FADD, MVT::f64,         2 }, // Pentium IV from http://www.agner.org/
990 
991     { ISD::FSUB, MVT::f32,         2 }, // Pentium IV from http://www.agner.org/
992     { ISD::FSUB, MVT::f64,         2 }, // Pentium IV from http://www.agner.org/
993   };
994 
995   if (ST->hasSSE2())
996     if (const auto *Entry = CostTableLookup(SSE2CostTable, ISD, LT.second))
997       return LT.first * Entry->Cost;
998 
999   static const CostTblEntry SSE1CostTable[] = {
1000     { ISD::FDIV, MVT::f32,   17 }, // Pentium III from http://www.agner.org/
1001     { ISD::FDIV, MVT::v4f32, 34 }, // Pentium III from http://www.agner.org/
1002 
1003     { ISD::FNEG, MVT::f32,    2 }, // Pentium III from http://www.agner.org/
1004     { ISD::FNEG, MVT::v4f32,  2 }, // Pentium III from http://www.agner.org/
1005 
1006     { ISD::FADD, MVT::f32,    1 }, // Pentium III from http://www.agner.org/
1007     { ISD::FADD, MVT::v4f32,  2 }, // Pentium III from http://www.agner.org/
1008 
1009     { ISD::FSUB, MVT::f32,    1 }, // Pentium III from http://www.agner.org/
1010     { ISD::FSUB, MVT::v4f32,  2 }, // Pentium III from http://www.agner.org/
1011   };
1012 
1013   if (ST->hasSSE1())
1014     if (const auto *Entry = CostTableLookup(SSE1CostTable, ISD, LT.second))
1015       return LT.first * Entry->Cost;
1016 
1017   static const CostTblEntry X64CostTbl[] = { // 64-bit targets
1018     { ISD::ADD,  MVT::i64,    1 }, // Core (Merom) from http://www.agner.org/
1019     { ISD::SUB,  MVT::i64,    1 }, // Core (Merom) from http://www.agner.org/
1020     { ISD::MUL,  MVT::i64,    2 }, // Nehalem 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,   3 },
2632     { ISD::BITREVERSE, MVT::v16i32,  3 },
2633     { ISD::BITREVERSE, MVT::v32i16,  3 },
2634     { ISD::BITREVERSE, MVT::v64i8,   2 },
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::v2i64,   3 },
2762     { ISD::BITREVERSE, MVT::v4i64,   3 },
2763     { ISD::BITREVERSE, MVT::v4i32,   3 },
2764     { ISD::BITREVERSE, MVT::v8i32,   3 },
2765     { ISD::BITREVERSE, MVT::v8i16,   3 },
2766     { ISD::BITREVERSE, MVT::v16i16,  3 },
2767     { ISD::BITREVERSE, MVT::v16i8,   3 },
2768     { ISD::BITREVERSE, MVT::v32i8,   3 },
2769     { ISD::BSWAP,      MVT::v4i64,   1 },
2770     { ISD::BSWAP,      MVT::v8i32,   1 },
2771     { ISD::BSWAP,      MVT::v16i16,  1 },
2772     { ISD::CTLZ,       MVT::v2i64,   7 },
2773     { ISD::CTLZ,       MVT::v4i64,   7 },
2774     { ISD::CTLZ,       MVT::v4i32,   5 },
2775     { ISD::CTLZ,       MVT::v8i32,   5 },
2776     { ISD::CTLZ,       MVT::v8i16,   4 },
2777     { ISD::CTLZ,       MVT::v16i16,  4 },
2778     { ISD::CTLZ,       MVT::v16i8,   3 },
2779     { ISD::CTLZ,       MVT::v32i8,   3 },
2780     { ISD::CTPOP,      MVT::v2i64,   3 },
2781     { ISD::CTPOP,      MVT::v4i64,   3 },
2782     { ISD::CTPOP,      MVT::v4i32,   7 },
2783     { ISD::CTPOP,      MVT::v8i32,   7 },
2784     { ISD::CTPOP,      MVT::v8i16,   3 },
2785     { ISD::CTPOP,      MVT::v16i16,  3 },
2786     { ISD::CTPOP,      MVT::v16i8,   2 },
2787     { ISD::CTPOP,      MVT::v32i8,   2 },
2788     { ISD::CTTZ,       MVT::v2i64,   4 },
2789     { ISD::CTTZ,       MVT::v4i64,   4 },
2790     { ISD::CTTZ,       MVT::v4i32,   7 },
2791     { ISD::CTTZ,       MVT::v8i32,   7 },
2792     { ISD::CTTZ,       MVT::v8i16,   4 },
2793     { ISD::CTTZ,       MVT::v16i16,  4 },
2794     { ISD::CTTZ,       MVT::v16i8,   3 },
2795     { ISD::CTTZ,       MVT::v32i8,   3 },
2796     { ISD::SADDSAT,    MVT::v16i16,  1 },
2797     { ISD::SADDSAT,    MVT::v32i8,   1 },
2798     { ISD::SMAX,       MVT::v8i32,   1 },
2799     { ISD::SMAX,       MVT::v16i16,  1 },
2800     { ISD::SMAX,       MVT::v32i8,   1 },
2801     { ISD::SMIN,       MVT::v8i32,   1 },
2802     { ISD::SMIN,       MVT::v16i16,  1 },
2803     { ISD::SMIN,       MVT::v32i8,   1 },
2804     { ISD::SSUBSAT,    MVT::v16i16,  1 },
2805     { ISD::SSUBSAT,    MVT::v32i8,   1 },
2806     { ISD::UADDSAT,    MVT::v16i16,  1 },
2807     { ISD::UADDSAT,    MVT::v32i8,   1 },
2808     { ISD::UADDSAT,    MVT::v8i32,   3 }, // not + pminud + paddd
2809     { ISD::UMAX,       MVT::v8i32,   1 },
2810     { ISD::UMAX,       MVT::v16i16,  1 },
2811     { ISD::UMAX,       MVT::v32i8,   1 },
2812     { ISD::UMIN,       MVT::v8i32,   1 },
2813     { ISD::UMIN,       MVT::v16i16,  1 },
2814     { ISD::UMIN,       MVT::v32i8,   1 },
2815     { ISD::USUBSAT,    MVT::v16i16,  1 },
2816     { ISD::USUBSAT,    MVT::v32i8,   1 },
2817     { ISD::USUBSAT,    MVT::v8i32,   2 }, // pmaxud + psubd
2818     { ISD::FMAXNUM,    MVT::v8f32,   3 }, // MAXPS + CMPUNORDPS + BLENDVPS
2819     { ISD::FMAXNUM,    MVT::v4f64,   3 }, // MAXPD + CMPUNORDPD + BLENDVPD
2820     { ISD::FSQRT,      MVT::f32,     7 }, // Haswell from http://www.agner.org/
2821     { ISD::FSQRT,      MVT::v4f32,   7 }, // Haswell from http://www.agner.org/
2822     { ISD::FSQRT,      MVT::v8f32,  14 }, // Haswell from http://www.agner.org/
2823     { ISD::FSQRT,      MVT::f64,    14 }, // Haswell from http://www.agner.org/
2824     { ISD::FSQRT,      MVT::v2f64,  14 }, // Haswell from http://www.agner.org/
2825     { ISD::FSQRT,      MVT::v4f64,  28 }, // Haswell from http://www.agner.org/
2826   };
2827   static const CostTblEntry AVX1CostTbl[] = {
2828     { ISD::ABS,        MVT::v4i64,   5 }, // VBLENDVPD(X,VPSUBQ(0,X),X)
2829     { ISD::ABS,        MVT::v8i32,   3 },
2830     { ISD::ABS,        MVT::v16i16,  3 },
2831     { ISD::ABS,        MVT::v32i8,   3 },
2832     { ISD::BITREVERSE, MVT::v4i64,  12 }, // 2 x 128-bit Op + extract/insert
2833     { ISD::BITREVERSE, MVT::v8i32,  12 }, // 2 x 128-bit Op + extract/insert
2834     { ISD::BITREVERSE, MVT::v16i16, 12 }, // 2 x 128-bit Op + extract/insert
2835     { ISD::BITREVERSE, MVT::v32i8,  12 }, // 2 x 128-bit Op + extract/insert
2836     { ISD::BSWAP,      MVT::v4i64,   4 },
2837     { ISD::BSWAP,      MVT::v8i32,   4 },
2838     { ISD::BSWAP,      MVT::v16i16,  4 },
2839     { ISD::CTLZ,       MVT::v4i64,  48 }, // 2 x 128-bit Op + extract/insert
2840     { ISD::CTLZ,       MVT::v8i32,  38 }, // 2 x 128-bit Op + extract/insert
2841     { ISD::CTLZ,       MVT::v16i16, 30 }, // 2 x 128-bit Op + extract/insert
2842     { ISD::CTLZ,       MVT::v32i8,  20 }, // 2 x 128-bit Op + extract/insert
2843     { ISD::CTPOP,      MVT::v4i64,  16 }, // 2 x 128-bit Op + extract/insert
2844     { ISD::CTPOP,      MVT::v8i32,  24 }, // 2 x 128-bit Op + extract/insert
2845     { ISD::CTPOP,      MVT::v16i16, 20 }, // 2 x 128-bit Op + extract/insert
2846     { ISD::CTPOP,      MVT::v32i8,  14 }, // 2 x 128-bit Op + extract/insert
2847     { ISD::CTTZ,       MVT::v4i64,  22 }, // 2 x 128-bit Op + extract/insert
2848     { ISD::CTTZ,       MVT::v8i32,  30 }, // 2 x 128-bit Op + extract/insert
2849     { ISD::CTTZ,       MVT::v16i16, 26 }, // 2 x 128-bit Op + extract/insert
2850     { ISD::CTTZ,       MVT::v32i8,  20 }, // 2 x 128-bit Op + extract/insert
2851     { ISD::SADDSAT,    MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2852     { ISD::SADDSAT,    MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2853     { ISD::SMAX,       MVT::v8i32,   4 }, // 2 x 128-bit Op + extract/insert
2854     { ISD::SMAX,       MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2855     { ISD::SMAX,       MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2856     { ISD::SMIN,       MVT::v8i32,   4 }, // 2 x 128-bit Op + extract/insert
2857     { ISD::SMIN,       MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2858     { ISD::SMIN,       MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2859     { ISD::SSUBSAT,    MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2860     { ISD::SSUBSAT,    MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2861     { ISD::UADDSAT,    MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2862     { ISD::UADDSAT,    MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2863     { ISD::UADDSAT,    MVT::v8i32,   8 }, // 2 x 128-bit Op + extract/insert
2864     { ISD::UMAX,       MVT::v8i32,   4 }, // 2 x 128-bit Op + extract/insert
2865     { ISD::UMAX,       MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2866     { ISD::UMAX,       MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2867     { ISD::UMIN,       MVT::v8i32,   4 }, // 2 x 128-bit Op + extract/insert
2868     { ISD::UMIN,       MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2869     { ISD::UMIN,       MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2870     { ISD::USUBSAT,    MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2871     { ISD::USUBSAT,    MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2872     { ISD::USUBSAT,    MVT::v8i32,   6 }, // 2 x 128-bit Op + extract/insert
2873     { ISD::FMAXNUM,    MVT::f32,     3 }, // MAXSS + CMPUNORDSS + BLENDVPS
2874     { ISD::FMAXNUM,    MVT::v4f32,   3 }, // MAXPS + CMPUNORDPS + BLENDVPS
2875     { ISD::FMAXNUM,    MVT::v8f32,   5 }, // MAXPS + CMPUNORDPS + BLENDVPS + ?
2876     { ISD::FMAXNUM,    MVT::f64,     3 }, // MAXSD + CMPUNORDSD + BLENDVPD
2877     { ISD::FMAXNUM,    MVT::v2f64,   3 }, // MAXPD + CMPUNORDPD + BLENDVPD
2878     { ISD::FMAXNUM,    MVT::v4f64,   5 }, // MAXPD + CMPUNORDPD + BLENDVPD + ?
2879     { ISD::FSQRT,      MVT::f32,    14 }, // SNB from http://www.agner.org/
2880     { ISD::FSQRT,      MVT::v4f32,  14 }, // SNB from http://www.agner.org/
2881     { ISD::FSQRT,      MVT::v8f32,  28 }, // SNB from http://www.agner.org/
2882     { ISD::FSQRT,      MVT::f64,    21 }, // SNB from http://www.agner.org/
2883     { ISD::FSQRT,      MVT::v2f64,  21 }, // SNB from http://www.agner.org/
2884     { ISD::FSQRT,      MVT::v4f64,  43 }, // SNB from http://www.agner.org/
2885   };
2886   static const CostTblEntry GLMCostTbl[] = {
2887     { ISD::FSQRT, MVT::f32,   19 }, // sqrtss
2888     { ISD::FSQRT, MVT::v4f32, 37 }, // sqrtps
2889     { ISD::FSQRT, MVT::f64,   34 }, // sqrtsd
2890     { ISD::FSQRT, MVT::v2f64, 67 }, // sqrtpd
2891   };
2892   static const CostTblEntry SLMCostTbl[] = {
2893     { ISD::FSQRT, MVT::f32,   20 }, // sqrtss
2894     { ISD::FSQRT, MVT::v4f32, 40 }, // sqrtps
2895     { ISD::FSQRT, MVT::f64,   35 }, // sqrtsd
2896     { ISD::FSQRT, MVT::v2f64, 70 }, // sqrtpd
2897   };
2898   static const CostTblEntry SSE42CostTbl[] = {
2899     { ISD::USUBSAT,    MVT::v4i32,   2 }, // pmaxud + psubd
2900     { ISD::UADDSAT,    MVT::v4i32,   3 }, // not + pminud + paddd
2901     { ISD::FSQRT,      MVT::f32,    18 }, // Nehalem from http://www.agner.org/
2902     { ISD::FSQRT,      MVT::v4f32,  18 }, // Nehalem from http://www.agner.org/
2903   };
2904   static const CostTblEntry SSE41CostTbl[] = {
2905     { ISD::ABS,        MVT::v2i64,   2 }, // BLENDVPD(X,PSUBQ(0,X),X)
2906     { ISD::SMAX,       MVT::v4i32,   1 },
2907     { ISD::SMAX,       MVT::v16i8,   1 },
2908     { ISD::SMIN,       MVT::v4i32,   1 },
2909     { ISD::SMIN,       MVT::v16i8,   1 },
2910     { ISD::UMAX,       MVT::v4i32,   1 },
2911     { ISD::UMAX,       MVT::v8i16,   1 },
2912     { ISD::UMIN,       MVT::v4i32,   1 },
2913     { ISD::UMIN,       MVT::v8i16,   1 },
2914   };
2915   static const CostTblEntry SSSE3CostTbl[] = {
2916     { ISD::ABS,        MVT::v4i32,   1 },
2917     { ISD::ABS,        MVT::v8i16,   1 },
2918     { ISD::ABS,        MVT::v16i8,   1 },
2919     { ISD::BITREVERSE, MVT::v2i64,   5 },
2920     { ISD::BITREVERSE, MVT::v4i32,   5 },
2921     { ISD::BITREVERSE, MVT::v8i16,   5 },
2922     { ISD::BITREVERSE, MVT::v16i8,   5 },
2923     { ISD::BSWAP,      MVT::v2i64,   1 },
2924     { ISD::BSWAP,      MVT::v4i32,   1 },
2925     { ISD::BSWAP,      MVT::v8i16,   1 },
2926     { ISD::CTLZ,       MVT::v2i64,  23 },
2927     { ISD::CTLZ,       MVT::v4i32,  18 },
2928     { ISD::CTLZ,       MVT::v8i16,  14 },
2929     { ISD::CTLZ,       MVT::v16i8,   9 },
2930     { ISD::CTPOP,      MVT::v2i64,   7 },
2931     { ISD::CTPOP,      MVT::v4i32,  11 },
2932     { ISD::CTPOP,      MVT::v8i16,   9 },
2933     { ISD::CTPOP,      MVT::v16i8,   6 },
2934     { ISD::CTTZ,       MVT::v2i64,  10 },
2935     { ISD::CTTZ,       MVT::v4i32,  14 },
2936     { ISD::CTTZ,       MVT::v8i16,  12 },
2937     { ISD::CTTZ,       MVT::v16i8,   9 }
2938   };
2939   static const CostTblEntry SSE2CostTbl[] = {
2940     { ISD::ABS,        MVT::v2i64,   4 },
2941     { ISD::ABS,        MVT::v4i32,   3 },
2942     { ISD::ABS,        MVT::v8i16,   2 },
2943     { ISD::ABS,        MVT::v16i8,   2 },
2944     { ISD::BITREVERSE, MVT::v2i64,  29 },
2945     { ISD::BITREVERSE, MVT::v4i32,  27 },
2946     { ISD::BITREVERSE, MVT::v8i16,  27 },
2947     { ISD::BITREVERSE, MVT::v16i8,  20 },
2948     { ISD::BSWAP,      MVT::v2i64,   7 },
2949     { ISD::BSWAP,      MVT::v4i32,   7 },
2950     { ISD::BSWAP,      MVT::v8i16,   7 },
2951     { ISD::CTLZ,       MVT::v2i64,  25 },
2952     { ISD::CTLZ,       MVT::v4i32,  26 },
2953     { ISD::CTLZ,       MVT::v8i16,  20 },
2954     { ISD::CTLZ,       MVT::v16i8,  17 },
2955     { ISD::CTPOP,      MVT::v2i64,  12 },
2956     { ISD::CTPOP,      MVT::v4i32,  15 },
2957     { ISD::CTPOP,      MVT::v8i16,  13 },
2958     { ISD::CTPOP,      MVT::v16i8,  10 },
2959     { ISD::CTTZ,       MVT::v2i64,  14 },
2960     { ISD::CTTZ,       MVT::v4i32,  18 },
2961     { ISD::CTTZ,       MVT::v8i16,  16 },
2962     { ISD::CTTZ,       MVT::v16i8,  13 },
2963     { ISD::SADDSAT,    MVT::v8i16,   1 },
2964     { ISD::SADDSAT,    MVT::v16i8,   1 },
2965     { ISD::SMAX,       MVT::v8i16,   1 },
2966     { ISD::SMIN,       MVT::v8i16,   1 },
2967     { ISD::SSUBSAT,    MVT::v8i16,   1 },
2968     { ISD::SSUBSAT,    MVT::v16i8,   1 },
2969     { ISD::UADDSAT,    MVT::v8i16,   1 },
2970     { ISD::UADDSAT,    MVT::v16i8,   1 },
2971     { ISD::UMAX,       MVT::v8i16,   2 },
2972     { ISD::UMAX,       MVT::v16i8,   1 },
2973     { ISD::UMIN,       MVT::v8i16,   2 },
2974     { ISD::UMIN,       MVT::v16i8,   1 },
2975     { ISD::USUBSAT,    MVT::v8i16,   1 },
2976     { ISD::USUBSAT,    MVT::v16i8,   1 },
2977     { ISD::FMAXNUM,    MVT::f64,     4 },
2978     { ISD::FMAXNUM,    MVT::v2f64,   4 },
2979     { ISD::FSQRT,      MVT::f64,    32 }, // Nehalem from http://www.agner.org/
2980     { ISD::FSQRT,      MVT::v2f64,  32 }, // Nehalem from http://www.agner.org/
2981   };
2982   static const CostTblEntry SSE1CostTbl[] = {
2983     { ISD::FMAXNUM,    MVT::f32,     4 },
2984     { ISD::FMAXNUM,    MVT::v4f32,   4 },
2985     { ISD::FSQRT,      MVT::f32,    28 }, // Pentium III from http://www.agner.org/
2986     { ISD::FSQRT,      MVT::v4f32,  56 }, // Pentium III from http://www.agner.org/
2987   };
2988   static const CostTblEntry BMI64CostTbl[] = { // 64-bit targets
2989     { ISD::CTTZ,       MVT::i64,     1 },
2990   };
2991   static const CostTblEntry BMI32CostTbl[] = { // 32 or 64-bit targets
2992     { ISD::CTTZ,       MVT::i32,     1 },
2993     { ISD::CTTZ,       MVT::i16,     1 },
2994     { ISD::CTTZ,       MVT::i8,      1 },
2995   };
2996   static const CostTblEntry LZCNT64CostTbl[] = { // 64-bit targets
2997     { ISD::CTLZ,       MVT::i64,     1 },
2998   };
2999   static const CostTblEntry LZCNT32CostTbl[] = { // 32 or 64-bit targets
3000     { ISD::CTLZ,       MVT::i32,     1 },
3001     { ISD::CTLZ,       MVT::i16,     1 },
3002     { ISD::CTLZ,       MVT::i8,      1 },
3003   };
3004   static const CostTblEntry POPCNT64CostTbl[] = { // 64-bit targets
3005     { ISD::CTPOP,      MVT::i64,     1 },
3006   };
3007   static const CostTblEntry POPCNT32CostTbl[] = { // 32 or 64-bit targets
3008     { ISD::CTPOP,      MVT::i32,     1 },
3009     { ISD::CTPOP,      MVT::i16,     1 },
3010     { ISD::CTPOP,      MVT::i8,      1 },
3011   };
3012   static const CostTblEntry X64CostTbl[] = { // 64-bit targets
3013     { ISD::ABS,        MVT::i64,     2 }, // SUB+CMOV
3014     { ISD::BITREVERSE, MVT::i64,    14 },
3015     { ISD::BSWAP,      MVT::i64,     1 },
3016     { ISD::CTLZ,       MVT::i64,     4 }, // BSR+XOR or BSR+XOR+CMOV
3017     { ISD::CTTZ,       MVT::i64,     3 }, // TEST+BSF+CMOV/BRANCH
3018     { ISD::CTPOP,      MVT::i64,    10 },
3019     { ISD::SADDO,      MVT::i64,     1 },
3020     { ISD::UADDO,      MVT::i64,     1 },
3021     { ISD::UMULO,      MVT::i64,     2 }, // mulq + seto
3022   };
3023   static const CostTblEntry X86CostTbl[] = { // 32 or 64-bit targets
3024     { ISD::ABS,        MVT::i32,     2 }, // SUB+CMOV
3025     { ISD::ABS,        MVT::i16,     2 }, // SUB+CMOV
3026     { ISD::BITREVERSE, MVT::i32,    14 },
3027     { ISD::BITREVERSE, MVT::i16,    14 },
3028     { ISD::BITREVERSE, MVT::i8,     11 },
3029     { ISD::BSWAP,      MVT::i32,     1 },
3030     { ISD::BSWAP,      MVT::i16,     1 }, // ROL
3031     { ISD::CTLZ,       MVT::i32,     4 }, // BSR+XOR or BSR+XOR+CMOV
3032     { ISD::CTLZ,       MVT::i16,     4 }, // BSR+XOR or BSR+XOR+CMOV
3033     { ISD::CTLZ,       MVT::i8,      4 }, // BSR+XOR or BSR+XOR+CMOV
3034     { ISD::CTTZ,       MVT::i32,     3 }, // TEST+BSF+CMOV/BRANCH
3035     { ISD::CTTZ,       MVT::i16,     3 }, // TEST+BSF+CMOV/BRANCH
3036     { ISD::CTTZ,       MVT::i8,      3 }, // TEST+BSF+CMOV/BRANCH
3037     { ISD::CTPOP,      MVT::i32,     8 },
3038     { ISD::CTPOP,      MVT::i16,     9 },
3039     { ISD::CTPOP,      MVT::i8,      7 },
3040     { ISD::SADDO,      MVT::i32,     1 },
3041     { ISD::SADDO,      MVT::i16,     1 },
3042     { ISD::SADDO,      MVT::i8,      1 },
3043     { ISD::UADDO,      MVT::i32,     1 },
3044     { ISD::UADDO,      MVT::i16,     1 },
3045     { ISD::UADDO,      MVT::i8,      1 },
3046     { ISD::UMULO,      MVT::i32,     2 }, // mul + seto
3047     { ISD::UMULO,      MVT::i16,     2 },
3048     { ISD::UMULO,      MVT::i8,      2 },
3049   };
3050 
3051   Type *RetTy = ICA.getReturnType();
3052   Type *OpTy = RetTy;
3053   Intrinsic::ID IID = ICA.getID();
3054   unsigned ISD = ISD::DELETED_NODE;
3055   switch (IID) {
3056   default:
3057     break;
3058   case Intrinsic::abs:
3059     ISD = ISD::ABS;
3060     break;
3061   case Intrinsic::bitreverse:
3062     ISD = ISD::BITREVERSE;
3063     break;
3064   case Intrinsic::bswap:
3065     ISD = ISD::BSWAP;
3066     break;
3067   case Intrinsic::ctlz:
3068     ISD = ISD::CTLZ;
3069     break;
3070   case Intrinsic::ctpop:
3071     ISD = ISD::CTPOP;
3072     break;
3073   case Intrinsic::cttz:
3074     ISD = ISD::CTTZ;
3075     break;
3076   case Intrinsic::maxnum:
3077   case Intrinsic::minnum:
3078     // FMINNUM has same costs so don't duplicate.
3079     ISD = ISD::FMAXNUM;
3080     break;
3081   case Intrinsic::sadd_sat:
3082     ISD = ISD::SADDSAT;
3083     break;
3084   case Intrinsic::smax:
3085     ISD = ISD::SMAX;
3086     break;
3087   case Intrinsic::smin:
3088     ISD = ISD::SMIN;
3089     break;
3090   case Intrinsic::ssub_sat:
3091     ISD = ISD::SSUBSAT;
3092     break;
3093   case Intrinsic::uadd_sat:
3094     ISD = ISD::UADDSAT;
3095     break;
3096   case Intrinsic::umax:
3097     ISD = ISD::UMAX;
3098     break;
3099   case Intrinsic::umin:
3100     ISD = ISD::UMIN;
3101     break;
3102   case Intrinsic::usub_sat:
3103     ISD = ISD::USUBSAT;
3104     break;
3105   case Intrinsic::sqrt:
3106     ISD = ISD::FSQRT;
3107     break;
3108   case Intrinsic::sadd_with_overflow:
3109   case Intrinsic::ssub_with_overflow:
3110     // SSUBO has same costs so don't duplicate.
3111     ISD = ISD::SADDO;
3112     OpTy = RetTy->getContainedType(0);
3113     break;
3114   case Intrinsic::uadd_with_overflow:
3115   case Intrinsic::usub_with_overflow:
3116     // USUBO has same costs so don't duplicate.
3117     ISD = ISD::UADDO;
3118     OpTy = RetTy->getContainedType(0);
3119     break;
3120   case Intrinsic::umul_with_overflow:
3121   case Intrinsic::smul_with_overflow:
3122     // SMULO has same costs so don't duplicate.
3123     ISD = ISD::UMULO;
3124     OpTy = RetTy->getContainedType(0);
3125     break;
3126   }
3127 
3128   if (ISD != ISD::DELETED_NODE) {
3129     // Legalize the type.
3130     std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, OpTy);
3131     MVT MTy = LT.second;
3132 
3133     // Attempt to lookup cost.
3134     if (ISD == ISD::BITREVERSE && ST->hasGFNI() && ST->hasSSSE3() &&
3135         MTy.isVector()) {
3136       // With PSHUFB the code is very similar for all types. If we have integer
3137       // byte operations, we just need a GF2P8AFFINEQB for vXi8. For other types
3138       // we also need a PSHUFB.
3139       unsigned Cost = MTy.getVectorElementType() == MVT::i8 ? 1 : 2;
3140 
3141       // Without byte operations, we need twice as many GF2P8AFFINEQB and PSHUFB
3142       // instructions. We also need an extract and an insert.
3143       if (!(MTy.is128BitVector() || (ST->hasAVX2() && MTy.is256BitVector()) ||
3144             (ST->hasBWI() && MTy.is512BitVector())))
3145         Cost = Cost * 2 + 2;
3146 
3147       return LT.first * Cost;
3148     }
3149 
3150     auto adjustTableCost = [](const CostTblEntry &Entry,
3151                               InstructionCost LegalizationCost,
3152                               FastMathFlags FMF) {
3153       // If there are no NANs to deal with, then these are reduced to a
3154       // single MIN** or MAX** instruction instead of the MIN/CMP/SELECT that we
3155       // assume is used in the non-fast case.
3156       if (Entry.ISD == ISD::FMAXNUM || Entry.ISD == ISD::FMINNUM) {
3157         if (FMF.noNaNs())
3158           return LegalizationCost * 1;
3159       }
3160       return LegalizationCost * (int)Entry.Cost;
3161     };
3162 
3163     if (ST->useGLMDivSqrtCosts())
3164       if (const auto *Entry = CostTableLookup(GLMCostTbl, ISD, MTy))
3165         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3166 
3167     if (ST->isSLM())
3168       if (const auto *Entry = CostTableLookup(SLMCostTbl, ISD, MTy))
3169         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3170 
3171     if (ST->hasBITALG())
3172       if (const auto *Entry = CostTableLookup(AVX512BITALGCostTbl, ISD, MTy))
3173         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3174 
3175     if (ST->hasVPOPCNTDQ())
3176       if (const auto *Entry = CostTableLookup(AVX512VPOPCNTDQCostTbl, ISD, MTy))
3177         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3178 
3179     if (ST->hasCDI())
3180       if (const auto *Entry = CostTableLookup(AVX512CDCostTbl, ISD, MTy))
3181         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3182 
3183     if (ST->hasBWI())
3184       if (const auto *Entry = CostTableLookup(AVX512BWCostTbl, ISD, MTy))
3185         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3186 
3187     if (ST->hasAVX512())
3188       if (const auto *Entry = CostTableLookup(AVX512CostTbl, ISD, MTy))
3189         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3190 
3191     if (ST->hasXOP())
3192       if (const auto *Entry = CostTableLookup(XOPCostTbl, ISD, MTy))
3193         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3194 
3195     if (ST->hasAVX2())
3196       if (const auto *Entry = CostTableLookup(AVX2CostTbl, ISD, MTy))
3197         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3198 
3199     if (ST->hasAVX())
3200       if (const auto *Entry = CostTableLookup(AVX1CostTbl, ISD, MTy))
3201         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3202 
3203     if (ST->hasSSE42())
3204       if (const auto *Entry = CostTableLookup(SSE42CostTbl, ISD, MTy))
3205         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3206 
3207     if (ST->hasSSE41())
3208       if (const auto *Entry = CostTableLookup(SSE41CostTbl, ISD, MTy))
3209         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3210 
3211     if (ST->hasSSSE3())
3212       if (const auto *Entry = CostTableLookup(SSSE3CostTbl, ISD, MTy))
3213         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3214 
3215     if (ST->hasSSE2())
3216       if (const auto *Entry = CostTableLookup(SSE2CostTbl, ISD, MTy))
3217         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3218 
3219     if (ST->hasSSE1())
3220       if (const auto *Entry = CostTableLookup(SSE1CostTbl, ISD, MTy))
3221         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3222 
3223     if (ST->hasBMI()) {
3224       if (ST->is64Bit())
3225         if (const auto *Entry = CostTableLookup(BMI64CostTbl, ISD, MTy))
3226           return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3227 
3228       if (const auto *Entry = CostTableLookup(BMI32CostTbl, ISD, MTy))
3229         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3230     }
3231 
3232     if (ST->hasLZCNT()) {
3233       if (ST->is64Bit())
3234         if (const auto *Entry = CostTableLookup(LZCNT64CostTbl, ISD, MTy))
3235           return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3236 
3237       if (const auto *Entry = CostTableLookup(LZCNT32CostTbl, ISD, MTy))
3238         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3239     }
3240 
3241     if (ST->hasPOPCNT()) {
3242       if (ST->is64Bit())
3243         if (const auto *Entry = CostTableLookup(POPCNT64CostTbl, ISD, MTy))
3244           return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3245 
3246       if (const auto *Entry = CostTableLookup(POPCNT32CostTbl, ISD, MTy))
3247         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3248     }
3249 
3250     if (ISD == ISD::BSWAP && ST->hasMOVBE() && ST->hasFastMOVBE()) {
3251       if (const Instruction *II = ICA.getInst()) {
3252         if (II->hasOneUse() && isa<StoreInst>(II->user_back()))
3253           return TTI::TCC_Free;
3254         if (auto *LI = dyn_cast<LoadInst>(II->getOperand(0))) {
3255           if (LI->hasOneUse())
3256             return TTI::TCC_Free;
3257         }
3258       }
3259     }
3260 
3261     // TODO - add BMI (TZCNT) scalar handling
3262 
3263     if (ST->is64Bit())
3264       if (const auto *Entry = CostTableLookup(X64CostTbl, ISD, MTy))
3265         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3266 
3267     if (const auto *Entry = CostTableLookup(X86CostTbl, ISD, MTy))
3268       return adjustTableCost(*Entry, LT.first, ICA.getFlags());
3269   }
3270 
3271   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
3272 }
3273 
3274 InstructionCost
3275 X86TTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
3276                                   TTI::TargetCostKind CostKind) {
3277   if (ICA.isTypeBasedOnly())
3278     return getTypeBasedIntrinsicInstrCost(ICA, CostKind);
3279 
3280   static const CostTblEntry AVX512CostTbl[] = {
3281     { ISD::ROTL,       MVT::v8i64,   1 },
3282     { ISD::ROTL,       MVT::v4i64,   1 },
3283     { ISD::ROTL,       MVT::v2i64,   1 },
3284     { ISD::ROTL,       MVT::v16i32,  1 },
3285     { ISD::ROTL,       MVT::v8i32,   1 },
3286     { ISD::ROTL,       MVT::v4i32,   1 },
3287     { ISD::ROTR,       MVT::v8i64,   1 },
3288     { ISD::ROTR,       MVT::v4i64,   1 },
3289     { ISD::ROTR,       MVT::v2i64,   1 },
3290     { ISD::ROTR,       MVT::v16i32,  1 },
3291     { ISD::ROTR,       MVT::v8i32,   1 },
3292     { ISD::ROTR,       MVT::v4i32,   1 }
3293   };
3294   // XOP: ROTL = VPROT(X,Y), ROTR = VPROT(X,SUB(0,Y))
3295   static const CostTblEntry XOPCostTbl[] = {
3296     { ISD::ROTL,       MVT::v4i64,   4 },
3297     { ISD::ROTL,       MVT::v8i32,   4 },
3298     { ISD::ROTL,       MVT::v16i16,  4 },
3299     { ISD::ROTL,       MVT::v32i8,   4 },
3300     { ISD::ROTL,       MVT::v2i64,   1 },
3301     { ISD::ROTL,       MVT::v4i32,   1 },
3302     { ISD::ROTL,       MVT::v8i16,   1 },
3303     { ISD::ROTL,       MVT::v16i8,   1 },
3304     { ISD::ROTR,       MVT::v4i64,   6 },
3305     { ISD::ROTR,       MVT::v8i32,   6 },
3306     { ISD::ROTR,       MVT::v16i16,  6 },
3307     { ISD::ROTR,       MVT::v32i8,   6 },
3308     { ISD::ROTR,       MVT::v2i64,   2 },
3309     { ISD::ROTR,       MVT::v4i32,   2 },
3310     { ISD::ROTR,       MVT::v8i16,   2 },
3311     { ISD::ROTR,       MVT::v16i8,   2 }
3312   };
3313   static const CostTblEntry X64CostTbl[] = { // 64-bit targets
3314     { ISD::ROTL,       MVT::i64,     1 },
3315     { ISD::ROTR,       MVT::i64,     1 },
3316     { ISD::FSHL,       MVT::i64,     4 }
3317   };
3318   static const CostTblEntry X86CostTbl[] = { // 32 or 64-bit targets
3319     { ISD::ROTL,       MVT::i32,     1 },
3320     { ISD::ROTL,       MVT::i16,     1 },
3321     { ISD::ROTL,       MVT::i8,      1 },
3322     { ISD::ROTR,       MVT::i32,     1 },
3323     { ISD::ROTR,       MVT::i16,     1 },
3324     { ISD::ROTR,       MVT::i8,      1 },
3325     { ISD::FSHL,       MVT::i32,     4 },
3326     { ISD::FSHL,       MVT::i16,     4 },
3327     { ISD::FSHL,       MVT::i8,      4 }
3328   };
3329 
3330   Intrinsic::ID IID = ICA.getID();
3331   Type *RetTy = ICA.getReturnType();
3332   const SmallVectorImpl<const Value *> &Args = ICA.getArgs();
3333   unsigned ISD = ISD::DELETED_NODE;
3334   switch (IID) {
3335   default:
3336     break;
3337   case Intrinsic::fshl:
3338     ISD = ISD::FSHL;
3339     if (Args[0] == Args[1])
3340       ISD = ISD::ROTL;
3341     break;
3342   case Intrinsic::fshr:
3343     // FSHR has same costs so don't duplicate.
3344     ISD = ISD::FSHL;
3345     if (Args[0] == Args[1])
3346       ISD = ISD::ROTR;
3347     break;
3348   }
3349 
3350   if (ISD != ISD::DELETED_NODE) {
3351     // Legalize the type.
3352     std::pair<InstructionCost, MVT> LT =
3353         TLI->getTypeLegalizationCost(DL, RetTy);
3354     MVT MTy = LT.second;
3355 
3356     // Attempt to lookup cost.
3357     if (ST->hasAVX512())
3358       if (const auto *Entry = CostTableLookup(AVX512CostTbl, ISD, MTy))
3359         return LT.first * Entry->Cost;
3360 
3361     if (ST->hasXOP())
3362       if (const auto *Entry = CostTableLookup(XOPCostTbl, ISD, MTy))
3363         return LT.first * Entry->Cost;
3364 
3365     if (ST->is64Bit())
3366       if (const auto *Entry = CostTableLookup(X64CostTbl, ISD, MTy))
3367         return LT.first * Entry->Cost;
3368 
3369     if (const auto *Entry = CostTableLookup(X86CostTbl, ISD, MTy))
3370       return LT.first * Entry->Cost;
3371   }
3372 
3373   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
3374 }
3375 
3376 InstructionCost X86TTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val,
3377                                                unsigned Index) {
3378   static const CostTblEntry SLMCostTbl[] = {
3379      { ISD::EXTRACT_VECTOR_ELT,       MVT::i8,      4 },
3380      { ISD::EXTRACT_VECTOR_ELT,       MVT::i16,     4 },
3381      { ISD::EXTRACT_VECTOR_ELT,       MVT::i32,     4 },
3382      { ISD::EXTRACT_VECTOR_ELT,       MVT::i64,     7 }
3383    };
3384 
3385   assert(Val->isVectorTy() && "This must be a vector type");
3386   Type *ScalarType = Val->getScalarType();
3387   int RegisterFileMoveCost = 0;
3388 
3389   // Non-immediate extraction/insertion can be handled as a sequence of
3390   // aliased loads+stores via the stack.
3391   if (Index == -1U && (Opcode == Instruction::ExtractElement ||
3392                        Opcode == Instruction::InsertElement)) {
3393     // TODO: On some SSE41+ targets, we expand to cmp+splat+select patterns:
3394     // inselt N0, N1, N2 --> select (SplatN2 == {0,1,2...}) ? SplatN1 : N0.
3395 
3396     // TODO: Move this to BasicTTIImpl.h? We'd need better gep + index handling.
3397     assert(isa<FixedVectorType>(Val) && "Fixed vector type expected");
3398     Align VecAlign = DL.getPrefTypeAlign(Val);
3399     Align SclAlign = DL.getPrefTypeAlign(ScalarType);
3400 
3401     // Extract - store vector to stack, load scalar.
3402     if (Opcode == Instruction::ExtractElement) {
3403       return getMemoryOpCost(Instruction::Store, Val, VecAlign, 0,
3404                              TTI::TargetCostKind::TCK_RecipThroughput) +
3405              getMemoryOpCost(Instruction::Load, ScalarType, SclAlign, 0,
3406                              TTI::TargetCostKind::TCK_RecipThroughput);
3407     }
3408     // Insert - store vector to stack, store scalar, load vector.
3409     if (Opcode == Instruction::InsertElement) {
3410       return getMemoryOpCost(Instruction::Store, Val, VecAlign, 0,
3411                              TTI::TargetCostKind::TCK_RecipThroughput) +
3412              getMemoryOpCost(Instruction::Store, ScalarType, SclAlign, 0,
3413                              TTI::TargetCostKind::TCK_RecipThroughput) +
3414              getMemoryOpCost(Instruction::Load, Val, VecAlign, 0,
3415                              TTI::TargetCostKind::TCK_RecipThroughput);
3416     }
3417   }
3418 
3419   if (Index != -1U && (Opcode == Instruction::ExtractElement ||
3420                        Opcode == Instruction::InsertElement)) {
3421     // Legalize the type.
3422     std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Val);
3423 
3424     // This type is legalized to a scalar type.
3425     if (!LT.second.isVector())
3426       return 0;
3427 
3428     // The type may be split. Normalize the index to the new type.
3429     unsigned NumElts = LT.second.getVectorNumElements();
3430     unsigned SubNumElts = NumElts;
3431     Index = Index % NumElts;
3432 
3433     // For >128-bit vectors, we need to extract higher 128-bit subvectors.
3434     // For inserts, we also need to insert the subvector back.
3435     if (LT.second.getSizeInBits() > 128) {
3436       assert((LT.second.getSizeInBits() % 128) == 0 && "Illegal vector");
3437       unsigned NumSubVecs = LT.second.getSizeInBits() / 128;
3438       SubNumElts = NumElts / NumSubVecs;
3439       if (SubNumElts <= Index) {
3440         RegisterFileMoveCost += (Opcode == Instruction::InsertElement ? 2 : 1);
3441         Index %= SubNumElts;
3442       }
3443     }
3444 
3445     if (Index == 0) {
3446       // Floating point scalars are already located in index #0.
3447       // Many insertions to #0 can fold away for scalar fp-ops, so let's assume
3448       // true for all.
3449       if (ScalarType->isFloatingPointTy())
3450         return RegisterFileMoveCost;
3451 
3452       // Assume movd/movq XMM -> GPR is relatively cheap on all targets.
3453       if (ScalarType->isIntegerTy() && Opcode == Instruction::ExtractElement)
3454         return 1 + RegisterFileMoveCost;
3455     }
3456 
3457     int ISD = TLI->InstructionOpcodeToISD(Opcode);
3458     assert(ISD && "Unexpected vector opcode");
3459     MVT MScalarTy = LT.second.getScalarType();
3460     if (ST->isSLM())
3461       if (auto *Entry = CostTableLookup(SLMCostTbl, ISD, MScalarTy))
3462         return Entry->Cost + RegisterFileMoveCost;
3463 
3464     // Assume pinsr/pextr XMM <-> GPR is relatively cheap on all targets.
3465     if ((MScalarTy == MVT::i16 && ST->hasSSE2()) ||
3466         (MScalarTy.isInteger() && ST->hasSSE41()))
3467       return 1 + RegisterFileMoveCost;
3468 
3469     // Assume insertps is relatively cheap on all targets.
3470     if (MScalarTy == MVT::f32 && ST->hasSSE41() &&
3471         Opcode == Instruction::InsertElement)
3472       return 1 + RegisterFileMoveCost;
3473 
3474     // For extractions we just need to shuffle the element to index 0, which
3475     // should be very cheap (assume cost = 1). For insertions we need to shuffle
3476     // the elements to its destination. In both cases we must handle the
3477     // subvector move(s).
3478     // If the vector type is already less than 128-bits then don't reduce it.
3479     // TODO: Under what circumstances should we shuffle using the full width?
3480     InstructionCost ShuffleCost = 1;
3481     if (Opcode == Instruction::InsertElement) {
3482       auto *SubTy = cast<VectorType>(Val);
3483       EVT VT = TLI->getValueType(DL, Val);
3484       if (VT.getScalarType() != MScalarTy || VT.getSizeInBits() >= 128)
3485         SubTy = FixedVectorType::get(ScalarType, SubNumElts);
3486       ShuffleCost =
3487           getShuffleCost(TTI::SK_PermuteTwoSrc, SubTy, None, 0, SubTy);
3488     }
3489     int IntOrFpCost = ScalarType->isFloatingPointTy() ? 0 : 1;
3490     return ShuffleCost + IntOrFpCost + RegisterFileMoveCost;
3491   }
3492 
3493   // Add to the base cost if we know that the extracted element of a vector is
3494   // destined to be moved to and used in the integer register file.
3495   if (Opcode == Instruction::ExtractElement && ScalarType->isPointerTy())
3496     RegisterFileMoveCost += 1;
3497 
3498   return BaseT::getVectorInstrCost(Opcode, Val, Index) + RegisterFileMoveCost;
3499 }
3500 
3501 InstructionCost X86TTIImpl::getScalarizationOverhead(VectorType *Ty,
3502                                                      const APInt &DemandedElts,
3503                                                      bool Insert,
3504                                                      bool Extract) {
3505   InstructionCost Cost = 0;
3506 
3507   // For insertions, a ISD::BUILD_VECTOR style vector initialization can be much
3508   // cheaper than an accumulation of ISD::INSERT_VECTOR_ELT.
3509   if (Insert) {
3510     std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
3511     MVT MScalarTy = LT.second.getScalarType();
3512 
3513     if ((MScalarTy == MVT::i16 && ST->hasSSE2()) ||
3514         (MScalarTy.isInteger() && ST->hasSSE41()) ||
3515         (MScalarTy == MVT::f32 && ST->hasSSE41())) {
3516       // For types we can insert directly, insertion into 128-bit sub vectors is
3517       // cheap, followed by a cheap chain of concatenations.
3518       if (LT.second.getSizeInBits() <= 128) {
3519         Cost +=
3520             BaseT::getScalarizationOverhead(Ty, DemandedElts, Insert, false);
3521       } else {
3522         // In each 128-lane, if at least one index is demanded but not all
3523         // indices are demanded and this 128-lane is not the first 128-lane of
3524         // the legalized-vector, then this 128-lane needs a extracti128; If in
3525         // each 128-lane, there is at least one demanded index, this 128-lane
3526         // needs a inserti128.
3527 
3528         // The following cases will help you build a better understanding:
3529         // Assume we insert several elements into a v8i32 vector in avx2,
3530         // Case#1: inserting into 1th index needs vpinsrd + inserti128.
3531         // Case#2: inserting into 5th index needs extracti128 + vpinsrd +
3532         // inserti128.
3533         // Case#3: inserting into 4,5,6,7 index needs 4*vpinsrd + inserti128.
3534         const int CostValue = *LT.first.getValue();
3535         assert(CostValue >= 0 && "Negative cost!");
3536         unsigned Num128Lanes = LT.second.getSizeInBits() / 128 * CostValue;
3537         unsigned NumElts = LT.second.getVectorNumElements() * CostValue;
3538         APInt WidenedDemandedElts = DemandedElts.zextOrSelf(NumElts);
3539         unsigned Scale = NumElts / Num128Lanes;
3540         // We iterate each 128-lane, and check if we need a
3541         // extracti128/inserti128 for this 128-lane.
3542         for (unsigned I = 0; I < NumElts; I += Scale) {
3543           APInt Mask = WidenedDemandedElts.getBitsSet(NumElts, I, I + Scale);
3544           APInt MaskedDE = Mask & WidenedDemandedElts;
3545           unsigned Population = MaskedDE.countPopulation();
3546           Cost += (Population > 0 && Population != Scale &&
3547                    I % LT.second.getVectorNumElements() != 0);
3548           Cost += Population > 0;
3549         }
3550         Cost += DemandedElts.countPopulation();
3551 
3552         // For vXf32 cases, insertion into the 0'th index in each v4f32
3553         // 128-bit vector is free.
3554         // NOTE: This assumes legalization widens vXf32 vectors.
3555         if (MScalarTy == MVT::f32)
3556           for (unsigned i = 0, e = cast<FixedVectorType>(Ty)->getNumElements();
3557                i < e; i += 4)
3558             if (DemandedElts[i])
3559               Cost--;
3560       }
3561     } else if (LT.second.isVector()) {
3562       // Without fast insertion, we need to use MOVD/MOVQ to pass each demanded
3563       // integer element as a SCALAR_TO_VECTOR, then we build the vector as a
3564       // series of UNPCK followed by CONCAT_VECTORS - all of these can be
3565       // considered cheap.
3566       if (Ty->isIntOrIntVectorTy())
3567         Cost += DemandedElts.countPopulation();
3568 
3569       // Get the smaller of the legalized or original pow2-extended number of
3570       // vector elements, which represents the number of unpacks we'll end up
3571       // performing.
3572       unsigned NumElts = LT.second.getVectorNumElements();
3573       unsigned Pow2Elts =
3574           PowerOf2Ceil(cast<FixedVectorType>(Ty)->getNumElements());
3575       Cost += (std::min<unsigned>(NumElts, Pow2Elts) - 1) * LT.first;
3576     }
3577   }
3578 
3579   // TODO: Use default extraction for now, but we should investigate extending this
3580   // to handle repeated subvector extraction.
3581   if (Extract)
3582     Cost += BaseT::getScalarizationOverhead(Ty, DemandedElts, false, Extract);
3583 
3584   return Cost;
3585 }
3586 
3587 InstructionCost X86TTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
3588                                             MaybeAlign Alignment,
3589                                             unsigned AddressSpace,
3590                                             TTI::TargetCostKind CostKind,
3591                                             const Instruction *I) {
3592   // TODO: Handle other cost kinds.
3593   if (CostKind != TTI::TCK_RecipThroughput) {
3594     if (auto *SI = dyn_cast_or_null<StoreInst>(I)) {
3595       // Store instruction with index and scale costs 2 Uops.
3596       // Check the preceding GEP to identify non-const indices.
3597       if (auto *GEP = dyn_cast<GetElementPtrInst>(SI->getPointerOperand())) {
3598         if (!all_of(GEP->indices(), [](Value *V) { return isa<Constant>(V); }))
3599           return TTI::TCC_Basic * 2;
3600       }
3601     }
3602     return TTI::TCC_Basic;
3603   }
3604 
3605   assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
3606          "Invalid Opcode");
3607   // Type legalization can't handle structs
3608   if (TLI->getValueType(DL, Src, true) == MVT::Other)
3609     return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
3610                                   CostKind);
3611 
3612   // Legalize the type.
3613   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
3614 
3615   auto *VTy = dyn_cast<FixedVectorType>(Src);
3616 
3617   // Handle the simple case of non-vectors.
3618   // NOTE: this assumes that legalization never creates vector from scalars!
3619   if (!VTy || !LT.second.isVector())
3620     // Each load/store unit costs 1.
3621     return LT.first * 1;
3622 
3623   bool IsLoad = Opcode == Instruction::Load;
3624 
3625   Type *EltTy = VTy->getElementType();
3626 
3627   const int EltTyBits = DL.getTypeSizeInBits(EltTy);
3628 
3629   InstructionCost Cost = 0;
3630 
3631   // Source of truth: how many elements were there in the original IR vector?
3632   const unsigned SrcNumElt = VTy->getNumElements();
3633 
3634   // How far have we gotten?
3635   int NumEltRemaining = SrcNumElt;
3636   // Note that we intentionally capture by-reference, NumEltRemaining changes.
3637   auto NumEltDone = [&]() { return SrcNumElt - NumEltRemaining; };
3638 
3639   const int MaxLegalOpSizeBytes = divideCeil(LT.second.getSizeInBits(), 8);
3640 
3641   // Note that even if we can store 64 bits of an XMM, we still operate on XMM.
3642   const unsigned XMMBits = 128;
3643   if (XMMBits % EltTyBits != 0)
3644     // Vector size must be a multiple of the element size. I.e. no padding.
3645     return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
3646                                   CostKind);
3647   const int NumEltPerXMM = XMMBits / EltTyBits;
3648 
3649   auto *XMMVecTy = FixedVectorType::get(EltTy, NumEltPerXMM);
3650 
3651   for (int CurrOpSizeBytes = MaxLegalOpSizeBytes, SubVecEltsLeft = 0;
3652        NumEltRemaining > 0; CurrOpSizeBytes /= 2) {
3653     // How many elements would a single op deal with at once?
3654     if ((8 * CurrOpSizeBytes) % EltTyBits != 0)
3655       // Vector size must be a multiple of the element size. I.e. no padding.
3656       return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
3657                                     CostKind);
3658     int CurrNumEltPerOp = (8 * CurrOpSizeBytes) / EltTyBits;
3659 
3660     assert(CurrOpSizeBytes > 0 && CurrNumEltPerOp > 0 && "How'd we get here?");
3661     assert((((NumEltRemaining * EltTyBits) < (2 * 8 * CurrOpSizeBytes)) ||
3662             (CurrOpSizeBytes == MaxLegalOpSizeBytes)) &&
3663            "Unless we haven't halved the op size yet, "
3664            "we have less than two op's sized units of work left.");
3665 
3666     auto *CurrVecTy = CurrNumEltPerOp > NumEltPerXMM
3667                           ? FixedVectorType::get(EltTy, CurrNumEltPerOp)
3668                           : XMMVecTy;
3669 
3670     assert(CurrVecTy->getNumElements() % CurrNumEltPerOp == 0 &&
3671            "After halving sizes, the vector elt count is no longer a multiple "
3672            "of number of elements per operation?");
3673     auto *CoalescedVecTy =
3674         CurrNumEltPerOp == 1
3675             ? CurrVecTy
3676             : FixedVectorType::get(
3677                   IntegerType::get(Src->getContext(),
3678                                    EltTyBits * CurrNumEltPerOp),
3679                   CurrVecTy->getNumElements() / CurrNumEltPerOp);
3680     assert(DL.getTypeSizeInBits(CoalescedVecTy) ==
3681                DL.getTypeSizeInBits(CurrVecTy) &&
3682            "coalesciing elements doesn't change vector width.");
3683 
3684     while (NumEltRemaining > 0) {
3685       assert(SubVecEltsLeft >= 0 && "Subreg element count overconsumtion?");
3686 
3687       // Can we use this vector size, as per the remaining element count?
3688       // Iff the vector is naturally aligned, we can do a wide load regardless.
3689       if (NumEltRemaining < CurrNumEltPerOp &&
3690           (!IsLoad || Alignment.valueOrOne() < CurrOpSizeBytes) &&
3691           CurrOpSizeBytes != 1)
3692         break; // Try smalled vector size.
3693 
3694       bool Is0thSubVec = (NumEltDone() % LT.second.getVectorNumElements()) == 0;
3695 
3696       // If we have fully processed the previous reg, we need to replenish it.
3697       if (SubVecEltsLeft == 0) {
3698         SubVecEltsLeft += CurrVecTy->getNumElements();
3699         // And that's free only for the 0'th subvector of a legalized vector.
3700         if (!Is0thSubVec)
3701           Cost += getShuffleCost(IsLoad ? TTI::ShuffleKind::SK_InsertSubvector
3702                                         : TTI::ShuffleKind::SK_ExtractSubvector,
3703                                  VTy, None, NumEltDone(), CurrVecTy);
3704       }
3705 
3706       // While we can directly load/store ZMM, YMM, and 64-bit halves of XMM,
3707       // for smaller widths (32/16/8) we have to insert/extract them separately.
3708       // Again, it's free for the 0'th subreg (if op is 32/64 bit wide,
3709       // but let's pretend that it is also true for 16/8 bit wide ops...)
3710       if (CurrOpSizeBytes <= 32 / 8 && !Is0thSubVec) {
3711         int NumEltDoneInCurrXMM = NumEltDone() % NumEltPerXMM;
3712         assert(NumEltDoneInCurrXMM % CurrNumEltPerOp == 0 && "");
3713         int CoalescedVecEltIdx = NumEltDoneInCurrXMM / CurrNumEltPerOp;
3714         APInt DemandedElts =
3715             APInt::getBitsSet(CoalescedVecTy->getNumElements(),
3716                               CoalescedVecEltIdx, CoalescedVecEltIdx + 1);
3717         assert(DemandedElts.countPopulation() == 1 && "Inserting single value");
3718         Cost += getScalarizationOverhead(CoalescedVecTy, DemandedElts, IsLoad,
3719                                          !IsLoad);
3720       }
3721 
3722       // This isn't exactly right. We're using slow unaligned 32-byte accesses
3723       // as a proxy for a double-pumped AVX memory interface such as on
3724       // Sandybridge.
3725       if (CurrOpSizeBytes == 32 && ST->isUnalignedMem32Slow())
3726         Cost += 2;
3727       else
3728         Cost += 1;
3729 
3730       SubVecEltsLeft -= CurrNumEltPerOp;
3731       NumEltRemaining -= CurrNumEltPerOp;
3732       Alignment = commonAlignment(Alignment.valueOrOne(), CurrOpSizeBytes);
3733     }
3734   }
3735 
3736   assert(NumEltRemaining <= 0 && "Should have processed all the elements.");
3737 
3738   return Cost;
3739 }
3740 
3741 InstructionCost
3742 X86TTIImpl::getMaskedMemoryOpCost(unsigned Opcode, Type *SrcTy, Align Alignment,
3743                                   unsigned AddressSpace,
3744                                   TTI::TargetCostKind CostKind) {
3745   bool IsLoad = (Instruction::Load == Opcode);
3746   bool IsStore = (Instruction::Store == Opcode);
3747 
3748   auto *SrcVTy = dyn_cast<FixedVectorType>(SrcTy);
3749   if (!SrcVTy)
3750     // To calculate scalar take the regular cost, without mask
3751     return getMemoryOpCost(Opcode, SrcTy, Alignment, AddressSpace, CostKind);
3752 
3753   unsigned NumElem = SrcVTy->getNumElements();
3754   auto *MaskTy =
3755       FixedVectorType::get(Type::getInt8Ty(SrcVTy->getContext()), NumElem);
3756   if ((IsLoad && !isLegalMaskedLoad(SrcVTy, Alignment)) ||
3757       (IsStore && !isLegalMaskedStore(SrcVTy, Alignment))) {
3758     // Scalarization
3759     APInt DemandedElts = APInt::getAllOnes(NumElem);
3760     InstructionCost MaskSplitCost =
3761         getScalarizationOverhead(MaskTy, DemandedElts, false, true);
3762     InstructionCost ScalarCompareCost = getCmpSelInstrCost(
3763         Instruction::ICmp, Type::getInt8Ty(SrcVTy->getContext()), nullptr,
3764         CmpInst::BAD_ICMP_PREDICATE, CostKind);
3765     InstructionCost BranchCost = getCFInstrCost(Instruction::Br, CostKind);
3766     InstructionCost MaskCmpCost = NumElem * (BranchCost + ScalarCompareCost);
3767     InstructionCost ValueSplitCost =
3768         getScalarizationOverhead(SrcVTy, DemandedElts, IsLoad, IsStore);
3769     InstructionCost MemopCost =
3770         NumElem * BaseT::getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
3771                                          Alignment, AddressSpace, CostKind);
3772     return MemopCost + ValueSplitCost + MaskSplitCost + MaskCmpCost;
3773   }
3774 
3775   // Legalize the type.
3776   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, SrcVTy);
3777   auto VT = TLI->getValueType(DL, SrcVTy);
3778   InstructionCost Cost = 0;
3779   if (VT.isSimple() && LT.second != VT.getSimpleVT() &&
3780       LT.second.getVectorNumElements() == NumElem)
3781     // Promotion requires extend/truncate for data and a shuffle for mask.
3782     Cost += getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVTy, None, 0, nullptr) +
3783             getShuffleCost(TTI::SK_PermuteTwoSrc, MaskTy, None, 0, nullptr);
3784 
3785   else if (LT.first * LT.second.getVectorNumElements() > NumElem) {
3786     auto *NewMaskTy = FixedVectorType::get(MaskTy->getElementType(),
3787                                            LT.second.getVectorNumElements());
3788     // Expanding requires fill mask with zeroes
3789     Cost += getShuffleCost(TTI::SK_InsertSubvector, NewMaskTy, None, 0, MaskTy);
3790   }
3791 
3792   // Pre-AVX512 - each maskmov load costs 2 + store costs ~8.
3793   if (!ST->hasAVX512())
3794     return Cost + LT.first * (IsLoad ? 2 : 8);
3795 
3796   // AVX-512 masked load/store is cheapper
3797   return Cost + LT.first;
3798 }
3799 
3800 InstructionCost X86TTIImpl::getAddressComputationCost(Type *Ty,
3801                                                       ScalarEvolution *SE,
3802                                                       const SCEV *Ptr) {
3803   // Address computations in vectorized code with non-consecutive addresses will
3804   // likely result in more instructions compared to scalar code where the
3805   // computation can more often be merged into the index mode. The resulting
3806   // extra micro-ops can significantly decrease throughput.
3807   const unsigned NumVectorInstToHideOverhead = 10;
3808 
3809   // Cost modeling of Strided Access Computation is hidden by the indexing
3810   // modes of X86 regardless of the stride value. We dont believe that there
3811   // is a difference between constant strided access in gerenal and constant
3812   // strided value which is less than or equal to 64.
3813   // Even in the case of (loop invariant) stride whose value is not known at
3814   // compile time, the address computation will not incur more than one extra
3815   // ADD instruction.
3816   if (Ty->isVectorTy() && SE) {
3817     if (!BaseT::isStridedAccess(Ptr))
3818       return NumVectorInstToHideOverhead;
3819     if (!BaseT::getConstantStrideStep(SE, Ptr))
3820       return 1;
3821   }
3822 
3823   return BaseT::getAddressComputationCost(Ty, SE, Ptr);
3824 }
3825 
3826 InstructionCost
3827 X86TTIImpl::getArithmeticReductionCost(unsigned Opcode, VectorType *ValTy,
3828                                        Optional<FastMathFlags> FMF,
3829                                        TTI::TargetCostKind CostKind) {
3830   if (TTI::requiresOrderedReduction(FMF))
3831     return BaseT::getArithmeticReductionCost(Opcode, ValTy, FMF, CostKind);
3832 
3833   // We use the Intel Architecture Code Analyzer(IACA) to measure the throughput
3834   // and make it as the cost.
3835 
3836   static const CostTblEntry SLMCostTblNoPairWise[] = {
3837     { ISD::FADD,  MVT::v2f64,   3 },
3838     { ISD::ADD,   MVT::v2i64,   5 },
3839   };
3840 
3841   static const CostTblEntry SSE2CostTblNoPairWise[] = {
3842     { ISD::FADD,  MVT::v2f64,   2 },
3843     { ISD::FADD,  MVT::v2f32,   2 },
3844     { ISD::FADD,  MVT::v4f32,   4 },
3845     { ISD::ADD,   MVT::v2i64,   2 },      // The data reported by the IACA tool is "1.6".
3846     { ISD::ADD,   MVT::v2i32,   2 }, // FIXME: chosen to be less than v4i32
3847     { ISD::ADD,   MVT::v4i32,   3 },      // The data reported by the IACA tool is "3.3".
3848     { ISD::ADD,   MVT::v2i16,   2 },      // The data reported by the IACA tool is "4.3".
3849     { ISD::ADD,   MVT::v4i16,   3 },      // The data reported by the IACA tool is "4.3".
3850     { ISD::ADD,   MVT::v8i16,   4 },      // The data reported by the IACA tool is "4.3".
3851     { ISD::ADD,   MVT::v2i8,    2 },
3852     { ISD::ADD,   MVT::v4i8,    2 },
3853     { ISD::ADD,   MVT::v8i8,    2 },
3854     { ISD::ADD,   MVT::v16i8,   3 },
3855   };
3856 
3857   static const CostTblEntry AVX1CostTblNoPairWise[] = {
3858     { ISD::FADD,  MVT::v4f64,   3 },
3859     { ISD::FADD,  MVT::v4f32,   3 },
3860     { ISD::FADD,  MVT::v8f32,   4 },
3861     { ISD::ADD,   MVT::v2i64,   1 },      // The data reported by the IACA tool is "1.5".
3862     { ISD::ADD,   MVT::v4i64,   3 },
3863     { ISD::ADD,   MVT::v8i32,   5 },
3864     { ISD::ADD,   MVT::v16i16,  5 },
3865     { ISD::ADD,   MVT::v32i8,   4 },
3866   };
3867 
3868   int ISD = TLI->InstructionOpcodeToISD(Opcode);
3869   assert(ISD && "Invalid opcode");
3870 
3871   // Before legalizing the type, give a chance to look up illegal narrow types
3872   // in the table.
3873   // FIXME: Is there a better way to do this?
3874   EVT VT = TLI->getValueType(DL, ValTy);
3875   if (VT.isSimple()) {
3876     MVT MTy = VT.getSimpleVT();
3877     if (ST->isSLM())
3878       if (const auto *Entry = CostTableLookup(SLMCostTblNoPairWise, ISD, MTy))
3879         return Entry->Cost;
3880 
3881     if (ST->hasAVX())
3882       if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
3883         return Entry->Cost;
3884 
3885     if (ST->hasSSE2())
3886       if (const auto *Entry = CostTableLookup(SSE2CostTblNoPairWise, ISD, MTy))
3887         return Entry->Cost;
3888   }
3889 
3890   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
3891 
3892   MVT MTy = LT.second;
3893 
3894   auto *ValVTy = cast<FixedVectorType>(ValTy);
3895 
3896   // Special case: vXi8 mul reductions are performed as vXi16.
3897   if (ISD == ISD::MUL && MTy.getScalarType() == MVT::i8) {
3898     auto *WideSclTy = IntegerType::get(ValVTy->getContext(), 16);
3899     auto *WideVecTy = FixedVectorType::get(WideSclTy, ValVTy->getNumElements());
3900     return getCastInstrCost(Instruction::ZExt, WideVecTy, ValTy,
3901                             TargetTransformInfo::CastContextHint::None,
3902                             CostKind) +
3903            getArithmeticReductionCost(Opcode, WideVecTy, FMF, CostKind);
3904   }
3905 
3906   InstructionCost ArithmeticCost = 0;
3907   if (LT.first != 1 && MTy.isVector() &&
3908       MTy.getVectorNumElements() < ValVTy->getNumElements()) {
3909     // Type needs to be split. We need LT.first - 1 arithmetic ops.
3910     auto *SingleOpTy = FixedVectorType::get(ValVTy->getElementType(),
3911                                             MTy.getVectorNumElements());
3912     ArithmeticCost = getArithmeticInstrCost(Opcode, SingleOpTy, CostKind);
3913     ArithmeticCost *= LT.first - 1;
3914   }
3915 
3916   if (ST->isSLM())
3917     if (const auto *Entry = CostTableLookup(SLMCostTblNoPairWise, ISD, MTy))
3918       return ArithmeticCost + Entry->Cost;
3919 
3920   if (ST->hasAVX())
3921     if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
3922       return ArithmeticCost + Entry->Cost;
3923 
3924   if (ST->hasSSE2())
3925     if (const auto *Entry = CostTableLookup(SSE2CostTblNoPairWise, ISD, MTy))
3926       return ArithmeticCost + Entry->Cost;
3927 
3928   // FIXME: These assume a naive kshift+binop lowering, which is probably
3929   // conservative in most cases.
3930   static const CostTblEntry AVX512BoolReduction[] = {
3931     { ISD::AND,  MVT::v2i1,   3 },
3932     { ISD::AND,  MVT::v4i1,   5 },
3933     { ISD::AND,  MVT::v8i1,   7 },
3934     { ISD::AND,  MVT::v16i1,  9 },
3935     { ISD::AND,  MVT::v32i1, 11 },
3936     { ISD::AND,  MVT::v64i1, 13 },
3937     { ISD::OR,   MVT::v2i1,   3 },
3938     { ISD::OR,   MVT::v4i1,   5 },
3939     { ISD::OR,   MVT::v8i1,   7 },
3940     { ISD::OR,   MVT::v16i1,  9 },
3941     { ISD::OR,   MVT::v32i1, 11 },
3942     { ISD::OR,   MVT::v64i1, 13 },
3943   };
3944 
3945   static const CostTblEntry AVX2BoolReduction[] = {
3946     { ISD::AND,  MVT::v16i16,  2 }, // vpmovmskb + cmp
3947     { ISD::AND,  MVT::v32i8,   2 }, // vpmovmskb + cmp
3948     { ISD::OR,   MVT::v16i16,  2 }, // vpmovmskb + cmp
3949     { ISD::OR,   MVT::v32i8,   2 }, // vpmovmskb + cmp
3950   };
3951 
3952   static const CostTblEntry AVX1BoolReduction[] = {
3953     { ISD::AND,  MVT::v4i64,   2 }, // vmovmskpd + cmp
3954     { ISD::AND,  MVT::v8i32,   2 }, // vmovmskps + cmp
3955     { ISD::AND,  MVT::v16i16,  4 }, // vextractf128 + vpand + vpmovmskb + cmp
3956     { ISD::AND,  MVT::v32i8,   4 }, // vextractf128 + vpand + vpmovmskb + cmp
3957     { ISD::OR,   MVT::v4i64,   2 }, // vmovmskpd + cmp
3958     { ISD::OR,   MVT::v8i32,   2 }, // vmovmskps + cmp
3959     { ISD::OR,   MVT::v16i16,  4 }, // vextractf128 + vpor + vpmovmskb + cmp
3960     { ISD::OR,   MVT::v32i8,   4 }, // vextractf128 + vpor + vpmovmskb + cmp
3961   };
3962 
3963   static const CostTblEntry SSE2BoolReduction[] = {
3964     { ISD::AND,  MVT::v2i64,   2 }, // movmskpd + cmp
3965     { ISD::AND,  MVT::v4i32,   2 }, // movmskps + cmp
3966     { ISD::AND,  MVT::v8i16,   2 }, // pmovmskb + cmp
3967     { ISD::AND,  MVT::v16i8,   2 }, // pmovmskb + cmp
3968     { ISD::OR,   MVT::v2i64,   2 }, // movmskpd + cmp
3969     { ISD::OR,   MVT::v4i32,   2 }, // movmskps + cmp
3970     { ISD::OR,   MVT::v8i16,   2 }, // pmovmskb + cmp
3971     { ISD::OR,   MVT::v16i8,   2 }, // pmovmskb + cmp
3972   };
3973 
3974   // Handle bool allof/anyof patterns.
3975   if (ValVTy->getElementType()->isIntegerTy(1)) {
3976     InstructionCost ArithmeticCost = 0;
3977     if (LT.first != 1 && MTy.isVector() &&
3978         MTy.getVectorNumElements() < ValVTy->getNumElements()) {
3979       // Type needs to be split. We need LT.first - 1 arithmetic ops.
3980       auto *SingleOpTy = FixedVectorType::get(ValVTy->getElementType(),
3981                                               MTy.getVectorNumElements());
3982       ArithmeticCost = getArithmeticInstrCost(Opcode, SingleOpTy, CostKind);
3983       ArithmeticCost *= LT.first - 1;
3984     }
3985 
3986     if (ST->hasAVX512())
3987       if (const auto *Entry = CostTableLookup(AVX512BoolReduction, ISD, MTy))
3988         return ArithmeticCost + Entry->Cost;
3989     if (ST->hasAVX2())
3990       if (const auto *Entry = CostTableLookup(AVX2BoolReduction, ISD, MTy))
3991         return ArithmeticCost + Entry->Cost;
3992     if (ST->hasAVX())
3993       if (const auto *Entry = CostTableLookup(AVX1BoolReduction, ISD, MTy))
3994         return ArithmeticCost + Entry->Cost;
3995     if (ST->hasSSE2())
3996       if (const auto *Entry = CostTableLookup(SSE2BoolReduction, ISD, MTy))
3997         return ArithmeticCost + Entry->Cost;
3998 
3999     return BaseT::getArithmeticReductionCost(Opcode, ValVTy, FMF, CostKind);
4000   }
4001 
4002   unsigned NumVecElts = ValVTy->getNumElements();
4003   unsigned ScalarSize = ValVTy->getScalarSizeInBits();
4004 
4005   // Special case power of 2 reductions where the scalar type isn't changed
4006   // by type legalization.
4007   if (!isPowerOf2_32(NumVecElts) || ScalarSize != MTy.getScalarSizeInBits())
4008     return BaseT::getArithmeticReductionCost(Opcode, ValVTy, FMF, CostKind);
4009 
4010   InstructionCost ReductionCost = 0;
4011 
4012   auto *Ty = ValVTy;
4013   if (LT.first != 1 && MTy.isVector() &&
4014       MTy.getVectorNumElements() < ValVTy->getNumElements()) {
4015     // Type needs to be split. We need LT.first - 1 arithmetic ops.
4016     Ty = FixedVectorType::get(ValVTy->getElementType(),
4017                               MTy.getVectorNumElements());
4018     ReductionCost = getArithmeticInstrCost(Opcode, Ty, CostKind);
4019     ReductionCost *= LT.first - 1;
4020     NumVecElts = MTy.getVectorNumElements();
4021   }
4022 
4023   // Now handle reduction with the legal type, taking into account size changes
4024   // at each level.
4025   while (NumVecElts > 1) {
4026     // Determine the size of the remaining vector we need to reduce.
4027     unsigned Size = NumVecElts * ScalarSize;
4028     NumVecElts /= 2;
4029     // If we're reducing from 256/512 bits, use an extract_subvector.
4030     if (Size > 128) {
4031       auto *SubTy = FixedVectorType::get(ValVTy->getElementType(), NumVecElts);
4032       ReductionCost +=
4033           getShuffleCost(TTI::SK_ExtractSubvector, Ty, None, NumVecElts, SubTy);
4034       Ty = SubTy;
4035     } else if (Size == 128) {
4036       // Reducing from 128 bits is a permute of v2f64/v2i64.
4037       FixedVectorType *ShufTy;
4038       if (ValVTy->isFloatingPointTy())
4039         ShufTy =
4040             FixedVectorType::get(Type::getDoubleTy(ValVTy->getContext()), 2);
4041       else
4042         ShufTy =
4043             FixedVectorType::get(Type::getInt64Ty(ValVTy->getContext()), 2);
4044       ReductionCost +=
4045           getShuffleCost(TTI::SK_PermuteSingleSrc, ShufTy, None, 0, nullptr);
4046     } else if (Size == 64) {
4047       // Reducing from 64 bits is a shuffle of v4f32/v4i32.
4048       FixedVectorType *ShufTy;
4049       if (ValVTy->isFloatingPointTy())
4050         ShufTy =
4051             FixedVectorType::get(Type::getFloatTy(ValVTy->getContext()), 4);
4052       else
4053         ShufTy =
4054             FixedVectorType::get(Type::getInt32Ty(ValVTy->getContext()), 4);
4055       ReductionCost +=
4056           getShuffleCost(TTI::SK_PermuteSingleSrc, ShufTy, None, 0, nullptr);
4057     } else {
4058       // Reducing from smaller size is a shift by immediate.
4059       auto *ShiftTy = FixedVectorType::get(
4060           Type::getIntNTy(ValVTy->getContext(), Size), 128 / Size);
4061       ReductionCost += getArithmeticInstrCost(
4062           Instruction::LShr, ShiftTy, CostKind,
4063           TargetTransformInfo::OK_AnyValue,
4064           TargetTransformInfo::OK_UniformConstantValue,
4065           TargetTransformInfo::OP_None, TargetTransformInfo::OP_None);
4066     }
4067 
4068     // Add the arithmetic op for this level.
4069     ReductionCost += getArithmeticInstrCost(Opcode, Ty, CostKind);
4070   }
4071 
4072   // Add the final extract element to the cost.
4073   return ReductionCost + getVectorInstrCost(Instruction::ExtractElement, Ty, 0);
4074 }
4075 
4076 InstructionCost X86TTIImpl::getMinMaxCost(Type *Ty, Type *CondTy,
4077                                           bool IsUnsigned) {
4078   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
4079 
4080   MVT MTy = LT.second;
4081 
4082   int ISD;
4083   if (Ty->isIntOrIntVectorTy()) {
4084     ISD = IsUnsigned ? ISD::UMIN : ISD::SMIN;
4085   } else {
4086     assert(Ty->isFPOrFPVectorTy() &&
4087            "Expected float point or integer vector type.");
4088     ISD = ISD::FMINNUM;
4089   }
4090 
4091   static const CostTblEntry SSE1CostTbl[] = {
4092     {ISD::FMINNUM, MVT::v4f32, 1},
4093   };
4094 
4095   static const CostTblEntry SSE2CostTbl[] = {
4096     {ISD::FMINNUM, MVT::v2f64, 1},
4097     {ISD::SMIN,    MVT::v8i16, 1},
4098     {ISD::UMIN,    MVT::v16i8, 1},
4099   };
4100 
4101   static const CostTblEntry SSE41CostTbl[] = {
4102     {ISD::SMIN,    MVT::v4i32, 1},
4103     {ISD::UMIN,    MVT::v4i32, 1},
4104     {ISD::UMIN,    MVT::v8i16, 1},
4105     {ISD::SMIN,    MVT::v16i8, 1},
4106   };
4107 
4108   static const CostTblEntry SSE42CostTbl[] = {
4109     {ISD::UMIN,    MVT::v2i64, 3}, // xor+pcmpgtq+blendvpd
4110   };
4111 
4112   static const CostTblEntry AVX1CostTbl[] = {
4113     {ISD::FMINNUM, MVT::v8f32,  1},
4114     {ISD::FMINNUM, MVT::v4f64,  1},
4115     {ISD::SMIN,    MVT::v8i32,  3},
4116     {ISD::UMIN,    MVT::v8i32,  3},
4117     {ISD::SMIN,    MVT::v16i16, 3},
4118     {ISD::UMIN,    MVT::v16i16, 3},
4119     {ISD::SMIN,    MVT::v32i8,  3},
4120     {ISD::UMIN,    MVT::v32i8,  3},
4121   };
4122 
4123   static const CostTblEntry AVX2CostTbl[] = {
4124     {ISD::SMIN,    MVT::v8i32,  1},
4125     {ISD::UMIN,    MVT::v8i32,  1},
4126     {ISD::SMIN,    MVT::v16i16, 1},
4127     {ISD::UMIN,    MVT::v16i16, 1},
4128     {ISD::SMIN,    MVT::v32i8,  1},
4129     {ISD::UMIN,    MVT::v32i8,  1},
4130   };
4131 
4132   static const CostTblEntry AVX512CostTbl[] = {
4133     {ISD::FMINNUM, MVT::v16f32, 1},
4134     {ISD::FMINNUM, MVT::v8f64,  1},
4135     {ISD::SMIN,    MVT::v2i64,  1},
4136     {ISD::UMIN,    MVT::v2i64,  1},
4137     {ISD::SMIN,    MVT::v4i64,  1},
4138     {ISD::UMIN,    MVT::v4i64,  1},
4139     {ISD::SMIN,    MVT::v8i64,  1},
4140     {ISD::UMIN,    MVT::v8i64,  1},
4141     {ISD::SMIN,    MVT::v16i32, 1},
4142     {ISD::UMIN,    MVT::v16i32, 1},
4143   };
4144 
4145   static const CostTblEntry AVX512BWCostTbl[] = {
4146     {ISD::SMIN,    MVT::v32i16, 1},
4147     {ISD::UMIN,    MVT::v32i16, 1},
4148     {ISD::SMIN,    MVT::v64i8,  1},
4149     {ISD::UMIN,    MVT::v64i8,  1},
4150   };
4151 
4152   // If we have a native MIN/MAX instruction for this type, use it.
4153   if (ST->hasBWI())
4154     if (const auto *Entry = CostTableLookup(AVX512BWCostTbl, ISD, MTy))
4155       return LT.first * Entry->Cost;
4156 
4157   if (ST->hasAVX512())
4158     if (const auto *Entry = CostTableLookup(AVX512CostTbl, ISD, MTy))
4159       return LT.first * Entry->Cost;
4160 
4161   if (ST->hasAVX2())
4162     if (const auto *Entry = CostTableLookup(AVX2CostTbl, ISD, MTy))
4163       return LT.first * Entry->Cost;
4164 
4165   if (ST->hasAVX())
4166     if (const auto *Entry = CostTableLookup(AVX1CostTbl, ISD, MTy))
4167       return LT.first * Entry->Cost;
4168 
4169   if (ST->hasSSE42())
4170     if (const auto *Entry = CostTableLookup(SSE42CostTbl, ISD, MTy))
4171       return LT.first * Entry->Cost;
4172 
4173   if (ST->hasSSE41())
4174     if (const auto *Entry = CostTableLookup(SSE41CostTbl, ISD, MTy))
4175       return LT.first * Entry->Cost;
4176 
4177   if (ST->hasSSE2())
4178     if (const auto *Entry = CostTableLookup(SSE2CostTbl, ISD, MTy))
4179       return LT.first * Entry->Cost;
4180 
4181   if (ST->hasSSE1())
4182     if (const auto *Entry = CostTableLookup(SSE1CostTbl, ISD, MTy))
4183       return LT.first * Entry->Cost;
4184 
4185   unsigned CmpOpcode;
4186   if (Ty->isFPOrFPVectorTy()) {
4187     CmpOpcode = Instruction::FCmp;
4188   } else {
4189     assert(Ty->isIntOrIntVectorTy() &&
4190            "expecting floating point or integer type for min/max reduction");
4191     CmpOpcode = Instruction::ICmp;
4192   }
4193 
4194   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4195   // Otherwise fall back to cmp+select.
4196   InstructionCost Result =
4197       getCmpSelInstrCost(CmpOpcode, Ty, CondTy, CmpInst::BAD_ICMP_PREDICATE,
4198                          CostKind) +
4199       getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
4200                          CmpInst::BAD_ICMP_PREDICATE, CostKind);
4201   return Result;
4202 }
4203 
4204 InstructionCost
4205 X86TTIImpl::getMinMaxReductionCost(VectorType *ValTy, VectorType *CondTy,
4206                                    bool IsUnsigned,
4207                                    TTI::TargetCostKind CostKind) {
4208   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
4209 
4210   MVT MTy = LT.second;
4211 
4212   int ISD;
4213   if (ValTy->isIntOrIntVectorTy()) {
4214     ISD = IsUnsigned ? ISD::UMIN : ISD::SMIN;
4215   } else {
4216     assert(ValTy->isFPOrFPVectorTy() &&
4217            "Expected float point or integer vector type.");
4218     ISD = ISD::FMINNUM;
4219   }
4220 
4221   // We use the Intel Architecture Code Analyzer(IACA) to measure the throughput
4222   // and make it as the cost.
4223 
4224   static const CostTblEntry SSE2CostTblNoPairWise[] = {
4225       {ISD::UMIN, MVT::v2i16, 5}, // need pxors to use pminsw/pmaxsw
4226       {ISD::UMIN, MVT::v4i16, 7}, // need pxors to use pminsw/pmaxsw
4227       {ISD::UMIN, MVT::v8i16, 9}, // need pxors to use pminsw/pmaxsw
4228   };
4229 
4230   static const CostTblEntry SSE41CostTblNoPairWise[] = {
4231       {ISD::SMIN, MVT::v2i16, 3}, // same as sse2
4232       {ISD::SMIN, MVT::v4i16, 5}, // same as sse2
4233       {ISD::UMIN, MVT::v2i16, 5}, // same as sse2
4234       {ISD::UMIN, MVT::v4i16, 7}, // same as sse2
4235       {ISD::SMIN, MVT::v8i16, 4}, // phminposuw+xor
4236       {ISD::UMIN, MVT::v8i16, 4}, // FIXME: umin is cheaper than umax
4237       {ISD::SMIN, MVT::v2i8,  3}, // pminsb
4238       {ISD::SMIN, MVT::v4i8,  5}, // pminsb
4239       {ISD::SMIN, MVT::v8i8,  7}, // pminsb
4240       {ISD::SMIN, MVT::v16i8, 6},
4241       {ISD::UMIN, MVT::v2i8,  3}, // same as sse2
4242       {ISD::UMIN, MVT::v4i8,  5}, // same as sse2
4243       {ISD::UMIN, MVT::v8i8,  7}, // same as sse2
4244       {ISD::UMIN, MVT::v16i8, 6}, // FIXME: umin is cheaper than umax
4245   };
4246 
4247   static const CostTblEntry AVX1CostTblNoPairWise[] = {
4248       {ISD::SMIN, MVT::v16i16, 6},
4249       {ISD::UMIN, MVT::v16i16, 6}, // FIXME: umin is cheaper than umax
4250       {ISD::SMIN, MVT::v32i8, 8},
4251       {ISD::UMIN, MVT::v32i8, 8},
4252   };
4253 
4254   static const CostTblEntry AVX512BWCostTblNoPairWise[] = {
4255       {ISD::SMIN, MVT::v32i16, 8},
4256       {ISD::UMIN, MVT::v32i16, 8}, // FIXME: umin is cheaper than umax
4257       {ISD::SMIN, MVT::v64i8, 10},
4258       {ISD::UMIN, MVT::v64i8, 10},
4259   };
4260 
4261   // Before legalizing the type, give a chance to look up illegal narrow types
4262   // in the table.
4263   // FIXME: Is there a better way to do this?
4264   EVT VT = TLI->getValueType(DL, ValTy);
4265   if (VT.isSimple()) {
4266     MVT MTy = VT.getSimpleVT();
4267     if (ST->hasBWI())
4268       if (const auto *Entry = CostTableLookup(AVX512BWCostTblNoPairWise, ISD, MTy))
4269         return Entry->Cost;
4270 
4271     if (ST->hasAVX())
4272       if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
4273         return Entry->Cost;
4274 
4275     if (ST->hasSSE41())
4276       if (const auto *Entry = CostTableLookup(SSE41CostTblNoPairWise, ISD, MTy))
4277         return Entry->Cost;
4278 
4279     if (ST->hasSSE2())
4280       if (const auto *Entry = CostTableLookup(SSE2CostTblNoPairWise, ISD, MTy))
4281         return Entry->Cost;
4282   }
4283 
4284   auto *ValVTy = cast<FixedVectorType>(ValTy);
4285   unsigned NumVecElts = ValVTy->getNumElements();
4286 
4287   auto *Ty = ValVTy;
4288   InstructionCost MinMaxCost = 0;
4289   if (LT.first != 1 && MTy.isVector() &&
4290       MTy.getVectorNumElements() < ValVTy->getNumElements()) {
4291     // Type needs to be split. We need LT.first - 1 operations ops.
4292     Ty = FixedVectorType::get(ValVTy->getElementType(),
4293                               MTy.getVectorNumElements());
4294     auto *SubCondTy = FixedVectorType::get(CondTy->getElementType(),
4295                                            MTy.getVectorNumElements());
4296     MinMaxCost = getMinMaxCost(Ty, SubCondTy, IsUnsigned);
4297     MinMaxCost *= LT.first - 1;
4298     NumVecElts = MTy.getVectorNumElements();
4299   }
4300 
4301   if (ST->hasBWI())
4302     if (const auto *Entry = CostTableLookup(AVX512BWCostTblNoPairWise, ISD, MTy))
4303       return MinMaxCost + Entry->Cost;
4304 
4305   if (ST->hasAVX())
4306     if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
4307       return MinMaxCost + Entry->Cost;
4308 
4309   if (ST->hasSSE41())
4310     if (const auto *Entry = CostTableLookup(SSE41CostTblNoPairWise, ISD, MTy))
4311       return MinMaxCost + Entry->Cost;
4312 
4313   if (ST->hasSSE2())
4314     if (const auto *Entry = CostTableLookup(SSE2CostTblNoPairWise, ISD, MTy))
4315       return MinMaxCost + Entry->Cost;
4316 
4317   unsigned ScalarSize = ValTy->getScalarSizeInBits();
4318 
4319   // Special case power of 2 reductions where the scalar type isn't changed
4320   // by type legalization.
4321   if (!isPowerOf2_32(ValVTy->getNumElements()) ||
4322       ScalarSize != MTy.getScalarSizeInBits())
4323     return BaseT::getMinMaxReductionCost(ValTy, CondTy, IsUnsigned, CostKind);
4324 
4325   // Now handle reduction with the legal type, taking into account size changes
4326   // at each level.
4327   while (NumVecElts > 1) {
4328     // Determine the size of the remaining vector we need to reduce.
4329     unsigned Size = NumVecElts * ScalarSize;
4330     NumVecElts /= 2;
4331     // If we're reducing from 256/512 bits, use an extract_subvector.
4332     if (Size > 128) {
4333       auto *SubTy = FixedVectorType::get(ValVTy->getElementType(), NumVecElts);
4334       MinMaxCost +=
4335           getShuffleCost(TTI::SK_ExtractSubvector, Ty, None, NumVecElts, SubTy);
4336       Ty = SubTy;
4337     } else if (Size == 128) {
4338       // Reducing from 128 bits is a permute of v2f64/v2i64.
4339       VectorType *ShufTy;
4340       if (ValTy->isFloatingPointTy())
4341         ShufTy =
4342             FixedVectorType::get(Type::getDoubleTy(ValTy->getContext()), 2);
4343       else
4344         ShufTy = FixedVectorType::get(Type::getInt64Ty(ValTy->getContext()), 2);
4345       MinMaxCost +=
4346           getShuffleCost(TTI::SK_PermuteSingleSrc, ShufTy, None, 0, nullptr);
4347     } else if (Size == 64) {
4348       // Reducing from 64 bits is a shuffle of v4f32/v4i32.
4349       FixedVectorType *ShufTy;
4350       if (ValTy->isFloatingPointTy())
4351         ShufTy = FixedVectorType::get(Type::getFloatTy(ValTy->getContext()), 4);
4352       else
4353         ShufTy = FixedVectorType::get(Type::getInt32Ty(ValTy->getContext()), 4);
4354       MinMaxCost +=
4355           getShuffleCost(TTI::SK_PermuteSingleSrc, ShufTy, None, 0, nullptr);
4356     } else {
4357       // Reducing from smaller size is a shift by immediate.
4358       auto *ShiftTy = FixedVectorType::get(
4359           Type::getIntNTy(ValTy->getContext(), Size), 128 / Size);
4360       MinMaxCost += getArithmeticInstrCost(
4361           Instruction::LShr, ShiftTy, TTI::TCK_RecipThroughput,
4362           TargetTransformInfo::OK_AnyValue,
4363           TargetTransformInfo::OK_UniformConstantValue,
4364           TargetTransformInfo::OP_None, TargetTransformInfo::OP_None);
4365     }
4366 
4367     // Add the arithmetic op for this level.
4368     auto *SubCondTy =
4369         FixedVectorType::get(CondTy->getElementType(), Ty->getNumElements());
4370     MinMaxCost += getMinMaxCost(Ty, SubCondTy, IsUnsigned);
4371   }
4372 
4373   // Add the final extract element to the cost.
4374   return MinMaxCost + getVectorInstrCost(Instruction::ExtractElement, Ty, 0);
4375 }
4376 
4377 /// Calculate the cost of materializing a 64-bit value. This helper
4378 /// method might only calculate a fraction of a larger immediate. Therefore it
4379 /// is valid to return a cost of ZERO.
4380 InstructionCost X86TTIImpl::getIntImmCost(int64_t Val) {
4381   if (Val == 0)
4382     return TTI::TCC_Free;
4383 
4384   if (isInt<32>(Val))
4385     return TTI::TCC_Basic;
4386 
4387   return 2 * TTI::TCC_Basic;
4388 }
4389 
4390 InstructionCost X86TTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
4391                                           TTI::TargetCostKind CostKind) {
4392   assert(Ty->isIntegerTy());
4393 
4394   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4395   if (BitSize == 0)
4396     return ~0U;
4397 
4398   // Never hoist constants larger than 128bit, because this might lead to
4399   // incorrect code generation or assertions in codegen.
4400   // Fixme: Create a cost model for types larger than i128 once the codegen
4401   // issues have been fixed.
4402   if (BitSize > 128)
4403     return TTI::TCC_Free;
4404 
4405   if (Imm == 0)
4406     return TTI::TCC_Free;
4407 
4408   // Sign-extend all constants to a multiple of 64-bit.
4409   APInt ImmVal = Imm;
4410   if (BitSize % 64 != 0)
4411     ImmVal = Imm.sext(alignTo(BitSize, 64));
4412 
4413   // Split the constant into 64-bit chunks and calculate the cost for each
4414   // chunk.
4415   InstructionCost Cost = 0;
4416   for (unsigned ShiftVal = 0; ShiftVal < BitSize; ShiftVal += 64) {
4417     APInt Tmp = ImmVal.ashr(ShiftVal).sextOrTrunc(64);
4418     int64_t Val = Tmp.getSExtValue();
4419     Cost += getIntImmCost(Val);
4420   }
4421   // We need at least one instruction to materialize the constant.
4422   return std::max<InstructionCost>(1, Cost);
4423 }
4424 
4425 InstructionCost X86TTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
4426                                               const APInt &Imm, Type *Ty,
4427                                               TTI::TargetCostKind CostKind,
4428                                               Instruction *Inst) {
4429   assert(Ty->isIntegerTy());
4430 
4431   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4432   // There is no cost model for constants with a bit size of 0. Return TCC_Free
4433   // here, so that constant hoisting will ignore this constant.
4434   if (BitSize == 0)
4435     return TTI::TCC_Free;
4436 
4437   unsigned ImmIdx = ~0U;
4438   switch (Opcode) {
4439   default:
4440     return TTI::TCC_Free;
4441   case Instruction::GetElementPtr:
4442     // Always hoist the base address of a GetElementPtr. This prevents the
4443     // creation of new constants for every base constant that gets constant
4444     // folded with the offset.
4445     if (Idx == 0)
4446       return 2 * TTI::TCC_Basic;
4447     return TTI::TCC_Free;
4448   case Instruction::Store:
4449     ImmIdx = 0;
4450     break;
4451   case Instruction::ICmp:
4452     // This is an imperfect hack to prevent constant hoisting of
4453     // compares that might be trying to check if a 64-bit value fits in
4454     // 32-bits. The backend can optimize these cases using a right shift by 32.
4455     // Ideally we would check the compare predicate here. There also other
4456     // similar immediates the backend can use shifts for.
4457     if (Idx == 1 && Imm.getBitWidth() == 64) {
4458       uint64_t ImmVal = Imm.getZExtValue();
4459       if (ImmVal == 0x100000000ULL || ImmVal == 0xffffffff)
4460         return TTI::TCC_Free;
4461     }
4462     ImmIdx = 1;
4463     break;
4464   case Instruction::And:
4465     // We support 64-bit ANDs with immediates with 32-bits of leading zeroes
4466     // by using a 32-bit operation with implicit zero extension. Detect such
4467     // immediates here as the normal path expects bit 31 to be sign extended.
4468     if (Idx == 1 && Imm.getBitWidth() == 64 && isUInt<32>(Imm.getZExtValue()))
4469       return TTI::TCC_Free;
4470     ImmIdx = 1;
4471     break;
4472   case Instruction::Add:
4473   case Instruction::Sub:
4474     // For add/sub, we can use the opposite instruction for INT32_MIN.
4475     if (Idx == 1 && Imm.getBitWidth() == 64 && Imm.getZExtValue() == 0x80000000)
4476       return TTI::TCC_Free;
4477     ImmIdx = 1;
4478     break;
4479   case Instruction::UDiv:
4480   case Instruction::SDiv:
4481   case Instruction::URem:
4482   case Instruction::SRem:
4483     // Division by constant is typically expanded later into a different
4484     // instruction sequence. This completely changes the constants.
4485     // Report them as "free" to stop ConstantHoist from marking them as opaque.
4486     return TTI::TCC_Free;
4487   case Instruction::Mul:
4488   case Instruction::Or:
4489   case Instruction::Xor:
4490     ImmIdx = 1;
4491     break;
4492   // Always return TCC_Free for the shift value of a shift instruction.
4493   case Instruction::Shl:
4494   case Instruction::LShr:
4495   case Instruction::AShr:
4496     if (Idx == 1)
4497       return TTI::TCC_Free;
4498     break;
4499   case Instruction::Trunc:
4500   case Instruction::ZExt:
4501   case Instruction::SExt:
4502   case Instruction::IntToPtr:
4503   case Instruction::PtrToInt:
4504   case Instruction::BitCast:
4505   case Instruction::PHI:
4506   case Instruction::Call:
4507   case Instruction::Select:
4508   case Instruction::Ret:
4509   case Instruction::Load:
4510     break;
4511   }
4512 
4513   if (Idx == ImmIdx) {
4514     int NumConstants = divideCeil(BitSize, 64);
4515     InstructionCost Cost = X86TTIImpl::getIntImmCost(Imm, Ty, CostKind);
4516     return (Cost <= NumConstants * TTI::TCC_Basic)
4517                ? static_cast<int>(TTI::TCC_Free)
4518                : Cost;
4519   }
4520 
4521   return X86TTIImpl::getIntImmCost(Imm, Ty, CostKind);
4522 }
4523 
4524 InstructionCost X86TTIImpl::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
4525                                                 const APInt &Imm, Type *Ty,
4526                                                 TTI::TargetCostKind CostKind) {
4527   assert(Ty->isIntegerTy());
4528 
4529   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4530   // There is no cost model for constants with a bit size of 0. Return TCC_Free
4531   // here, so that constant hoisting will ignore this constant.
4532   if (BitSize == 0)
4533     return TTI::TCC_Free;
4534 
4535   switch (IID) {
4536   default:
4537     return TTI::TCC_Free;
4538   case Intrinsic::sadd_with_overflow:
4539   case Intrinsic::uadd_with_overflow:
4540   case Intrinsic::ssub_with_overflow:
4541   case Intrinsic::usub_with_overflow:
4542   case Intrinsic::smul_with_overflow:
4543   case Intrinsic::umul_with_overflow:
4544     if ((Idx == 1) && Imm.getBitWidth() <= 64 && isInt<32>(Imm.getSExtValue()))
4545       return TTI::TCC_Free;
4546     break;
4547   case Intrinsic::experimental_stackmap:
4548     if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
4549       return TTI::TCC_Free;
4550     break;
4551   case Intrinsic::experimental_patchpoint_void:
4552   case Intrinsic::experimental_patchpoint_i64:
4553     if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
4554       return TTI::TCC_Free;
4555     break;
4556   }
4557   return X86TTIImpl::getIntImmCost(Imm, Ty, CostKind);
4558 }
4559 
4560 InstructionCost X86TTIImpl::getCFInstrCost(unsigned Opcode,
4561                                            TTI::TargetCostKind CostKind,
4562                                            const Instruction *I) {
4563   if (CostKind != TTI::TCK_RecipThroughput)
4564     return Opcode == Instruction::PHI ? 0 : 1;
4565   // Branches are assumed to be predicted.
4566   return 0;
4567 }
4568 
4569 int X86TTIImpl::getGatherOverhead() const {
4570   // Some CPUs have more overhead for gather. The specified overhead is relative
4571   // to the Load operation. "2" is the number provided by Intel architects. This
4572   // parameter is used for cost estimation of Gather Op and comparison with
4573   // other alternatives.
4574   // TODO: Remove the explicit hasAVX512()?, That would mean we would only
4575   // enable gather with a -march.
4576   if (ST->hasAVX512() || (ST->hasAVX2() && ST->hasFastGather()))
4577     return 2;
4578 
4579   return 1024;
4580 }
4581 
4582 int X86TTIImpl::getScatterOverhead() const {
4583   if (ST->hasAVX512())
4584     return 2;
4585 
4586   return 1024;
4587 }
4588 
4589 // Return an average cost of Gather / Scatter instruction, maybe improved later.
4590 // FIXME: Add TargetCostKind support.
4591 InstructionCost X86TTIImpl::getGSVectorCost(unsigned Opcode, Type *SrcVTy,
4592                                             const Value *Ptr, Align Alignment,
4593                                             unsigned AddressSpace) {
4594 
4595   assert(isa<VectorType>(SrcVTy) && "Unexpected type in getGSVectorCost");
4596   unsigned VF = cast<FixedVectorType>(SrcVTy)->getNumElements();
4597 
4598   // Try to reduce index size from 64 bit (default for GEP)
4599   // to 32. It is essential for VF 16. If the index can't be reduced to 32, the
4600   // operation will use 16 x 64 indices which do not fit in a zmm and needs
4601   // to split. Also check that the base pointer is the same for all lanes,
4602   // and that there's at most one variable index.
4603   auto getIndexSizeInBits = [](const Value *Ptr, const DataLayout &DL) {
4604     unsigned IndexSize = DL.getPointerSizeInBits();
4605     const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4606     if (IndexSize < 64 || !GEP)
4607       return IndexSize;
4608 
4609     unsigned NumOfVarIndices = 0;
4610     const Value *Ptrs = GEP->getPointerOperand();
4611     if (Ptrs->getType()->isVectorTy() && !getSplatValue(Ptrs))
4612       return IndexSize;
4613     for (unsigned i = 1; i < GEP->getNumOperands(); ++i) {
4614       if (isa<Constant>(GEP->getOperand(i)))
4615         continue;
4616       Type *IndxTy = GEP->getOperand(i)->getType();
4617       if (auto *IndexVTy = dyn_cast<VectorType>(IndxTy))
4618         IndxTy = IndexVTy->getElementType();
4619       if ((IndxTy->getPrimitiveSizeInBits() == 64 &&
4620           !isa<SExtInst>(GEP->getOperand(i))) ||
4621          ++NumOfVarIndices > 1)
4622         return IndexSize; // 64
4623     }
4624     return (unsigned)32;
4625   };
4626 
4627   // Trying to reduce IndexSize to 32 bits for vector 16.
4628   // By default the IndexSize is equal to pointer size.
4629   unsigned IndexSize = (ST->hasAVX512() && VF >= 16)
4630                            ? getIndexSizeInBits(Ptr, DL)
4631                            : DL.getPointerSizeInBits();
4632 
4633   auto *IndexVTy = FixedVectorType::get(
4634       IntegerType::get(SrcVTy->getContext(), IndexSize), VF);
4635   std::pair<InstructionCost, MVT> IdxsLT =
4636       TLI->getTypeLegalizationCost(DL, IndexVTy);
4637   std::pair<InstructionCost, MVT> SrcLT =
4638       TLI->getTypeLegalizationCost(DL, SrcVTy);
4639   InstructionCost::CostType SplitFactor =
4640       *std::max(IdxsLT.first, SrcLT.first).getValue();
4641   if (SplitFactor > 1) {
4642     // Handle splitting of vector of pointers
4643     auto *SplitSrcTy =
4644         FixedVectorType::get(SrcVTy->getScalarType(), VF / SplitFactor);
4645     return SplitFactor * getGSVectorCost(Opcode, SplitSrcTy, Ptr, Alignment,
4646                                          AddressSpace);
4647   }
4648 
4649   // The gather / scatter cost is given by Intel architects. It is a rough
4650   // number since we are looking at one instruction in a time.
4651   const int GSOverhead = (Opcode == Instruction::Load)
4652                              ? getGatherOverhead()
4653                              : getScatterOverhead();
4654   return GSOverhead + VF * getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
4655                                            MaybeAlign(Alignment), AddressSpace,
4656                                            TTI::TCK_RecipThroughput);
4657 }
4658 
4659 /// Return the cost of full scalarization of gather / scatter operation.
4660 ///
4661 /// Opcode - Load or Store instruction.
4662 /// SrcVTy - The type of the data vector that should be gathered or scattered.
4663 /// VariableMask - The mask is non-constant at compile time.
4664 /// Alignment - Alignment for one element.
4665 /// AddressSpace - pointer[s] address space.
4666 ///
4667 /// FIXME: Add TargetCostKind support.
4668 InstructionCost X86TTIImpl::getGSScalarCost(unsigned Opcode, Type *SrcVTy,
4669                                             bool VariableMask, Align Alignment,
4670                                             unsigned AddressSpace) {
4671   unsigned VF = cast<FixedVectorType>(SrcVTy)->getNumElements();
4672   APInt DemandedElts = APInt::getAllOnes(VF);
4673   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4674 
4675   InstructionCost MaskUnpackCost = 0;
4676   if (VariableMask) {
4677     auto *MaskTy =
4678         FixedVectorType::get(Type::getInt1Ty(SrcVTy->getContext()), VF);
4679     MaskUnpackCost =
4680         getScalarizationOverhead(MaskTy, DemandedElts, false, true);
4681     InstructionCost ScalarCompareCost = getCmpSelInstrCost(
4682         Instruction::ICmp, Type::getInt1Ty(SrcVTy->getContext()), nullptr,
4683         CmpInst::BAD_ICMP_PREDICATE, CostKind);
4684     InstructionCost BranchCost = getCFInstrCost(Instruction::Br, CostKind);
4685     MaskUnpackCost += VF * (BranchCost + ScalarCompareCost);
4686   }
4687 
4688   // The cost of the scalar loads/stores.
4689   InstructionCost MemoryOpCost =
4690       VF * getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
4691                            MaybeAlign(Alignment), AddressSpace, CostKind);
4692 
4693   InstructionCost InsertExtractCost = 0;
4694   if (Opcode == Instruction::Load)
4695     for (unsigned i = 0; i < VF; ++i)
4696       // Add the cost of inserting each scalar load into the vector
4697       InsertExtractCost +=
4698         getVectorInstrCost(Instruction::InsertElement, SrcVTy, i);
4699   else
4700     for (unsigned i = 0; i < VF; ++i)
4701       // Add the cost of extracting each element out of the data vector
4702       InsertExtractCost +=
4703         getVectorInstrCost(Instruction::ExtractElement, SrcVTy, i);
4704 
4705   return MemoryOpCost + MaskUnpackCost + InsertExtractCost;
4706 }
4707 
4708 /// Calculate the cost of Gather / Scatter operation
4709 InstructionCost X86TTIImpl::getGatherScatterOpCost(
4710     unsigned Opcode, Type *SrcVTy, const Value *Ptr, bool VariableMask,
4711     Align Alignment, TTI::TargetCostKind CostKind,
4712     const Instruction *I = nullptr) {
4713   if (CostKind != TTI::TCK_RecipThroughput) {
4714     if ((Opcode == Instruction::Load &&
4715          isLegalMaskedGather(SrcVTy, Align(Alignment))) ||
4716         (Opcode == Instruction::Store &&
4717          isLegalMaskedScatter(SrcVTy, Align(Alignment))))
4718       return 1;
4719     return BaseT::getGatherScatterOpCost(Opcode, SrcVTy, Ptr, VariableMask,
4720                                          Alignment, CostKind, I);
4721   }
4722 
4723   assert(SrcVTy->isVectorTy() && "Unexpected data type for Gather/Scatter");
4724   PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
4725   if (!PtrTy && Ptr->getType()->isVectorTy())
4726     PtrTy = dyn_cast<PointerType>(
4727         cast<VectorType>(Ptr->getType())->getElementType());
4728   assert(PtrTy && "Unexpected type for Ptr argument");
4729   unsigned AddressSpace = PtrTy->getAddressSpace();
4730 
4731   if ((Opcode == Instruction::Load &&
4732        !isLegalMaskedGather(SrcVTy, Align(Alignment))) ||
4733       (Opcode == Instruction::Store &&
4734        !isLegalMaskedScatter(SrcVTy, Align(Alignment))))
4735     return getGSScalarCost(Opcode, SrcVTy, VariableMask, Alignment,
4736                            AddressSpace);
4737 
4738   return getGSVectorCost(Opcode, SrcVTy, Ptr, Alignment, AddressSpace);
4739 }
4740 
4741 bool X86TTIImpl::isLSRCostLess(TargetTransformInfo::LSRCost &C1,
4742                                TargetTransformInfo::LSRCost &C2) {
4743     // X86 specific here are "instruction number 1st priority".
4744     return std::tie(C1.Insns, C1.NumRegs, C1.AddRecCost,
4745                     C1.NumIVMuls, C1.NumBaseAdds,
4746                     C1.ScaleCost, C1.ImmCost, C1.SetupCost) <
4747            std::tie(C2.Insns, C2.NumRegs, C2.AddRecCost,
4748                     C2.NumIVMuls, C2.NumBaseAdds,
4749                     C2.ScaleCost, C2.ImmCost, C2.SetupCost);
4750 }
4751 
4752 bool X86TTIImpl::canMacroFuseCmp() {
4753   return ST->hasMacroFusion() || ST->hasBranchFusion();
4754 }
4755 
4756 bool X86TTIImpl::isLegalMaskedLoad(Type *DataTy, Align Alignment) {
4757   if (!ST->hasAVX())
4758     return false;
4759 
4760   // The backend can't handle a single element vector.
4761   if (isa<VectorType>(DataTy) &&
4762       cast<FixedVectorType>(DataTy)->getNumElements() == 1)
4763     return false;
4764   Type *ScalarTy = DataTy->getScalarType();
4765 
4766   if (ScalarTy->isPointerTy())
4767     return true;
4768 
4769   if (ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
4770     return true;
4771 
4772   if (ScalarTy->isHalfTy() && ST->hasBWI() && ST->hasFP16())
4773     return true;
4774 
4775   if (!ScalarTy->isIntegerTy())
4776     return false;
4777 
4778   unsigned IntWidth = ScalarTy->getIntegerBitWidth();
4779   return IntWidth == 32 || IntWidth == 64 ||
4780          ((IntWidth == 8 || IntWidth == 16) && ST->hasBWI());
4781 }
4782 
4783 bool X86TTIImpl::isLegalMaskedStore(Type *DataType, Align Alignment) {
4784   return isLegalMaskedLoad(DataType, Alignment);
4785 }
4786 
4787 bool X86TTIImpl::isLegalNTLoad(Type *DataType, Align Alignment) {
4788   unsigned DataSize = DL.getTypeStoreSize(DataType);
4789   // The only supported nontemporal loads are for aligned vectors of 16 or 32
4790   // bytes.  Note that 32-byte nontemporal vector loads are supported by AVX2
4791   // (the equivalent stores only require AVX).
4792   if (Alignment >= DataSize && (DataSize == 16 || DataSize == 32))
4793     return DataSize == 16 ?  ST->hasSSE1() : ST->hasAVX2();
4794 
4795   return false;
4796 }
4797 
4798 bool X86TTIImpl::isLegalNTStore(Type *DataType, Align Alignment) {
4799   unsigned DataSize = DL.getTypeStoreSize(DataType);
4800 
4801   // SSE4A supports nontemporal stores of float and double at arbitrary
4802   // alignment.
4803   if (ST->hasSSE4A() && (DataType->isFloatTy() || DataType->isDoubleTy()))
4804     return true;
4805 
4806   // Besides the SSE4A subtarget exception above, only aligned stores are
4807   // available nontemporaly on any other subtarget.  And only stores with a size
4808   // of 4..32 bytes (powers of 2, only) are permitted.
4809   if (Alignment < DataSize || DataSize < 4 || DataSize > 32 ||
4810       !isPowerOf2_32(DataSize))
4811     return false;
4812 
4813   // 32-byte vector nontemporal stores are supported by AVX (the equivalent
4814   // loads require AVX2).
4815   if (DataSize == 32)
4816     return ST->hasAVX();
4817   if (DataSize == 16)
4818     return ST->hasSSE1();
4819   return true;
4820 }
4821 
4822 bool X86TTIImpl::isLegalMaskedExpandLoad(Type *DataTy) {
4823   if (!isa<VectorType>(DataTy))
4824     return false;
4825 
4826   if (!ST->hasAVX512())
4827     return false;
4828 
4829   // The backend can't handle a single element vector.
4830   if (cast<FixedVectorType>(DataTy)->getNumElements() == 1)
4831     return false;
4832 
4833   Type *ScalarTy = cast<VectorType>(DataTy)->getElementType();
4834 
4835   if (ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
4836     return true;
4837 
4838   if (!ScalarTy->isIntegerTy())
4839     return false;
4840 
4841   unsigned IntWidth = ScalarTy->getIntegerBitWidth();
4842   return IntWidth == 32 || IntWidth == 64 ||
4843          ((IntWidth == 8 || IntWidth == 16) && ST->hasVBMI2());
4844 }
4845 
4846 bool X86TTIImpl::isLegalMaskedCompressStore(Type *DataTy) {
4847   return isLegalMaskedExpandLoad(DataTy);
4848 }
4849 
4850 bool X86TTIImpl::isLegalMaskedGather(Type *DataTy, Align Alignment) {
4851   // Some CPUs have better gather performance than others.
4852   // TODO: Remove the explicit ST->hasAVX512()?, That would mean we would only
4853   // enable gather with a -march.
4854   if (!(ST->hasAVX512() || (ST->hasFastGather() && ST->hasAVX2())))
4855     return false;
4856 
4857   // This function is called now in two cases: from the Loop Vectorizer
4858   // and from the Scalarizer.
4859   // When the Loop Vectorizer asks about legality of the feature,
4860   // the vectorization factor is not calculated yet. The Loop Vectorizer
4861   // sends a scalar type and the decision is based on the width of the
4862   // scalar element.
4863   // Later on, the cost model will estimate usage this intrinsic based on
4864   // the vector type.
4865   // The Scalarizer asks again about legality. It sends a vector type.
4866   // In this case we can reject non-power-of-2 vectors.
4867   // We also reject single element vectors as the type legalizer can't
4868   // scalarize it.
4869   if (auto *DataVTy = dyn_cast<FixedVectorType>(DataTy)) {
4870     unsigned NumElts = DataVTy->getNumElements();
4871     if (NumElts == 1)
4872       return false;
4873     // Gather / Scatter for vector 2 is not profitable on KNL / SKX
4874     // Vector-4 of gather/scatter instruction does not exist on KNL.
4875     // We can extend it to 8 elements, but zeroing upper bits of
4876     // the mask vector will add more instructions. Right now we give the scalar
4877     // cost of vector-4 for KNL. TODO: Check, maybe the gather/scatter
4878     // instruction is better in the VariableMask case.
4879     if (ST->hasAVX512() && (NumElts == 2 || (NumElts == 4 && !ST->hasVLX())))
4880       return false;
4881   }
4882   Type *ScalarTy = DataTy->getScalarType();
4883   if (ScalarTy->isPointerTy())
4884     return true;
4885 
4886   if (ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
4887     return true;
4888 
4889   if (!ScalarTy->isIntegerTy())
4890     return false;
4891 
4892   unsigned IntWidth = ScalarTy->getIntegerBitWidth();
4893   return IntWidth == 32 || IntWidth == 64;
4894 }
4895 
4896 bool X86TTIImpl::isLegalMaskedScatter(Type *DataType, Align Alignment) {
4897   // AVX2 doesn't support scatter
4898   if (!ST->hasAVX512())
4899     return false;
4900   return isLegalMaskedGather(DataType, Alignment);
4901 }
4902 
4903 bool X86TTIImpl::hasDivRemOp(Type *DataType, bool IsSigned) {
4904   EVT VT = TLI->getValueType(DL, DataType);
4905   return TLI->isOperationLegal(IsSigned ? ISD::SDIVREM : ISD::UDIVREM, VT);
4906 }
4907 
4908 bool X86TTIImpl::isFCmpOrdCheaperThanFCmpZero(Type *Ty) {
4909   return false;
4910 }
4911 
4912 bool X86TTIImpl::areInlineCompatible(const Function *Caller,
4913                                      const Function *Callee) const {
4914   const TargetMachine &TM = getTLI()->getTargetMachine();
4915 
4916   // Work this as a subsetting of subtarget features.
4917   const FeatureBitset &CallerBits =
4918       TM.getSubtargetImpl(*Caller)->getFeatureBits();
4919   const FeatureBitset &CalleeBits =
4920       TM.getSubtargetImpl(*Callee)->getFeatureBits();
4921 
4922   FeatureBitset RealCallerBits = CallerBits & ~InlineFeatureIgnoreList;
4923   FeatureBitset RealCalleeBits = CalleeBits & ~InlineFeatureIgnoreList;
4924   return (RealCallerBits & RealCalleeBits) == RealCalleeBits;
4925 }
4926 
4927 bool X86TTIImpl::areFunctionArgsABICompatible(
4928     const Function *Caller, const Function *Callee,
4929     SmallPtrSetImpl<Argument *> &Args) const {
4930   if (!BaseT::areFunctionArgsABICompatible(Caller, Callee, Args))
4931     return false;
4932 
4933   // If we get here, we know the target features match. If one function
4934   // considers 512-bit vectors legal and the other does not, consider them
4935   // incompatible.
4936   const TargetMachine &TM = getTLI()->getTargetMachine();
4937 
4938   if (TM.getSubtarget<X86Subtarget>(*Caller).useAVX512Regs() ==
4939       TM.getSubtarget<X86Subtarget>(*Callee).useAVX512Regs())
4940     return true;
4941 
4942   // Consider the arguments compatible if they aren't vectors or aggregates.
4943   // FIXME: Look at the size of vectors.
4944   // FIXME: Look at the element types of aggregates to see if there are vectors.
4945   // FIXME: The API of this function seems intended to allow arguments
4946   // to be removed from the set, but the caller doesn't check if the set
4947   // becomes empty so that may not work in practice.
4948   return llvm::none_of(Args, [](Argument *A) {
4949     auto *EltTy = cast<PointerType>(A->getType())->getElementType();
4950     return EltTy->isVectorTy() || EltTy->isAggregateType();
4951   });
4952 }
4953 
4954 X86TTIImpl::TTI::MemCmpExpansionOptions
4955 X86TTIImpl::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const {
4956   TTI::MemCmpExpansionOptions Options;
4957   Options.MaxNumLoads = TLI->getMaxExpandSizeMemcmp(OptSize);
4958   Options.NumLoadsPerBlock = 2;
4959   // All GPR and vector loads can be unaligned.
4960   Options.AllowOverlappingLoads = true;
4961   if (IsZeroCmp) {
4962     // Only enable vector loads for equality comparison. Right now the vector
4963     // version is not as fast for three way compare (see #33329).
4964     const unsigned PreferredWidth = ST->getPreferVectorWidth();
4965     if (PreferredWidth >= 512 && ST->hasAVX512()) Options.LoadSizes.push_back(64);
4966     if (PreferredWidth >= 256 && ST->hasAVX()) Options.LoadSizes.push_back(32);
4967     if (PreferredWidth >= 128 && ST->hasSSE2()) Options.LoadSizes.push_back(16);
4968   }
4969   if (ST->is64Bit()) {
4970     Options.LoadSizes.push_back(8);
4971   }
4972   Options.LoadSizes.push_back(4);
4973   Options.LoadSizes.push_back(2);
4974   Options.LoadSizes.push_back(1);
4975   return Options;
4976 }
4977 
4978 bool X86TTIImpl::enableInterleavedAccessVectorization() {
4979   // TODO: We expect this to be beneficial regardless of arch,
4980   // but there are currently some unexplained performance artifacts on Atom.
4981   // As a temporary solution, disable on Atom.
4982   return !(ST->isAtom());
4983 }
4984 
4985 // Get estimation for interleaved load/store operations for AVX2.
4986 // \p Factor is the interleaved-access factor (stride) - number of
4987 // (interleaved) elements in the group.
4988 // \p Indices contains the indices for a strided load: when the
4989 // interleaved load has gaps they indicate which elements are used.
4990 // If Indices is empty (or if the number of indices is equal to the size
4991 // of the interleaved-access as given in \p Factor) the access has no gaps.
4992 //
4993 // As opposed to AVX-512, AVX2 does not have generic shuffles that allow
4994 // computing the cost using a generic formula as a function of generic
4995 // shuffles. We therefore use a lookup table instead, filled according to
4996 // the instruction sequences that codegen currently generates.
4997 InstructionCost X86TTIImpl::getInterleavedMemoryOpCostAVX2(
4998     unsigned Opcode, FixedVectorType *VecTy, unsigned Factor,
4999     ArrayRef<unsigned> Indices, Align Alignment, unsigned AddressSpace,
5000     TTI::TargetCostKind CostKind, bool UseMaskForCond, bool UseMaskForGaps) {
5001 
5002   if (UseMaskForCond || UseMaskForGaps)
5003     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
5004                                              Alignment, AddressSpace, CostKind,
5005                                              UseMaskForCond, UseMaskForGaps);
5006 
5007   // We currently Support only fully-interleaved groups, with no gaps.
5008   // TODO: Support also strided loads (interleaved-groups with gaps).
5009   if (Indices.size() && Indices.size() != Factor)
5010     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
5011                                              Alignment, AddressSpace, CostKind);
5012 
5013   // VecTy for interleave memop is <VF*Factor x Elt>.
5014   // So, for VF=4, Interleave Factor = 3, Element type = i32 we have
5015   // VecTy = <12 x i32>.
5016   MVT LegalVT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
5017 
5018   // This function can be called with VecTy=<6xi128>, Factor=3, in which case
5019   // the VF=2, while v2i128 is an unsupported MVT vector type
5020   // (see MachineValueType.h::getVectorVT()).
5021   if (!LegalVT.isVector())
5022     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
5023                                              Alignment, AddressSpace, CostKind);
5024 
5025   unsigned VF = VecTy->getNumElements() / Factor;
5026   Type *ScalarTy = VecTy->getElementType();
5027   // Deduplicate entries, model floats/pointers as appropriately-sized integers.
5028   if (!ScalarTy->isIntegerTy())
5029     ScalarTy =
5030         Type::getIntNTy(ScalarTy->getContext(), DL.getTypeSizeInBits(ScalarTy));
5031 
5032   // Get the cost of all the memory operations.
5033   InstructionCost MemOpCosts = getMemoryOpCost(
5034       Opcode, VecTy, MaybeAlign(Alignment), AddressSpace, CostKind);
5035 
5036   auto *VT = FixedVectorType::get(ScalarTy, VF);
5037   EVT ETy = TLI->getValueType(DL, VT);
5038   if (!ETy.isSimple())
5039     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
5040                                              Alignment, AddressSpace, CostKind);
5041 
5042   // TODO: Complete for other data-types and strides.
5043   // Each combination of Stride, element bit width and VF results in a different
5044   // sequence; The cost tables are therefore accessed with:
5045   // Factor (stride) and VectorType=VFxiN.
5046   // The Cost accounts only for the shuffle sequence;
5047   // The cost of the loads/stores is accounted for separately.
5048   //
5049   static const CostTblEntry AVX2InterleavedLoadTbl[] = {
5050       {2, MVT::v4i64, 6}, // (load 8i64 and) deinterleave into 2 x 4i64
5051 
5052       {3, MVT::v2i8, 10},  // (load 6i8 and) deinterleave into 3 x 2i8
5053       {3, MVT::v4i8, 4},   // (load 12i8 and) deinterleave into 3 x 4i8
5054       {3, MVT::v8i8, 9},   // (load 24i8 and) deinterleave into 3 x 8i8
5055       {3, MVT::v16i8, 11}, // (load 48i8 and) deinterleave into 3 x 16i8
5056       {3, MVT::v32i8, 13}, // (load 96i8 and) deinterleave into 3 x 32i8
5057 
5058       {3, MVT::v8i32, 17}, // (load 24i32 and) deinterleave into 3 x 8i32
5059 
5060       {4, MVT::v2i8, 12},  // (load 8i8 and) deinterleave into 4 x 2i8
5061       {4, MVT::v4i8, 4},   // (load 16i8 and) deinterleave into 4 x 4i8
5062       {4, MVT::v8i8, 20},  // (load 32i8 and) deinterleave into 4 x 8i8
5063       {4, MVT::v16i8, 39}, // (load 64i8 and) deinterleave into 4 x 16i8
5064       {4, MVT::v32i8, 80}, // (load 128i8 and) deinterleave into 4 x 32i8
5065 
5066       {8, MVT::v8i32, 40} // (load 64i32 and) deinterleave into 8 x 8i32
5067   };
5068 
5069   static const CostTblEntry AVX2InterleavedStoreTbl[] = {
5070       {2, MVT::v4i64, 6}, // interleave 2 x 4i64 into 8i64 (and store)
5071 
5072       {3, MVT::v2i8, 7},   // interleave 3 x 2i8 into 6i8 (and store)
5073       {3, MVT::v4i8, 8},   // interleave 3 x 4i8 into 12i8 (and store)
5074       {3, MVT::v8i8, 11},  // interleave 3 x 8i8 into 24i8 (and store)
5075       {3, MVT::v16i8, 11}, // interleave 3 x 16i8 into 48i8 (and store)
5076       {3, MVT::v32i8, 13}, // interleave 3 x 32i8 into 96i8 (and store)
5077 
5078       {4, MVT::v2i8, 12},  // interleave 4 x 2i8 into 8i8 (and store)
5079       {4, MVT::v4i8, 9},   // interleave 4 x 4i8 into 16i8 (and store)
5080       {4, MVT::v8i8, 10},  // interleave 4 x 8i8 into 32i8 (and store)
5081       {4, MVT::v16i8, 10}, // interleave 4 x 16i8 into 64i8 (and store)
5082       {4, MVT::v32i8, 12}  // interleave 4 x 32i8 into 128i8 (and store)
5083   };
5084 
5085   if (Opcode == Instruction::Load) {
5086     if (const auto *Entry =
5087             CostTableLookup(AVX2InterleavedLoadTbl, Factor, ETy.getSimpleVT()))
5088       return MemOpCosts + Entry->Cost;
5089   } else {
5090     assert(Opcode == Instruction::Store &&
5091            "Expected Store Instruction at this  point");
5092     if (const auto *Entry =
5093             CostTableLookup(AVX2InterleavedStoreTbl, Factor, ETy.getSimpleVT()))
5094       return MemOpCosts + Entry->Cost;
5095   }
5096 
5097   return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
5098                                            Alignment, AddressSpace, CostKind);
5099 }
5100 
5101 // Get estimation for interleaved load/store operations and strided load.
5102 // \p Indices contains indices for strided load.
5103 // \p Factor - the factor of interleaving.
5104 // AVX-512 provides 3-src shuffles that significantly reduces the cost.
5105 InstructionCost X86TTIImpl::getInterleavedMemoryOpCostAVX512(
5106     unsigned Opcode, FixedVectorType *VecTy, unsigned Factor,
5107     ArrayRef<unsigned> Indices, Align Alignment, unsigned AddressSpace,
5108     TTI::TargetCostKind CostKind, bool UseMaskForCond, bool UseMaskForGaps) {
5109 
5110   if (UseMaskForCond || UseMaskForGaps)
5111     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
5112                                              Alignment, AddressSpace, CostKind,
5113                                              UseMaskForCond, UseMaskForGaps);
5114 
5115   // VecTy for interleave memop is <VF*Factor x Elt>.
5116   // So, for VF=4, Interleave Factor = 3, Element type = i32 we have
5117   // VecTy = <12 x i32>.
5118 
5119   // Calculate the number of memory operations (NumOfMemOps), required
5120   // for load/store the VecTy.
5121   MVT LegalVT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
5122   unsigned VecTySize = DL.getTypeStoreSize(VecTy);
5123   unsigned LegalVTSize = LegalVT.getStoreSize();
5124   unsigned NumOfMemOps = (VecTySize + LegalVTSize - 1) / LegalVTSize;
5125 
5126   // Get the cost of one memory operation.
5127   auto *SingleMemOpTy = FixedVectorType::get(VecTy->getElementType(),
5128                                              LegalVT.getVectorNumElements());
5129   InstructionCost MemOpCost = getMemoryOpCost(
5130       Opcode, SingleMemOpTy, MaybeAlign(Alignment), AddressSpace, CostKind);
5131 
5132   unsigned VF = VecTy->getNumElements() / Factor;
5133   MVT VT = MVT::getVectorVT(MVT::getVT(VecTy->getScalarType()), VF);
5134 
5135   if (Opcode == Instruction::Load) {
5136     // The tables (AVX512InterleavedLoadTbl and AVX512InterleavedStoreTbl)
5137     // contain the cost of the optimized shuffle sequence that the
5138     // X86InterleavedAccess pass will generate.
5139     // The cost of loads and stores are computed separately from the table.
5140 
5141     // X86InterleavedAccess support only the following interleaved-access group.
5142     static const CostTblEntry AVX512InterleavedLoadTbl[] = {
5143         {3, MVT::v16i8, 12}, //(load 48i8 and) deinterleave into 3 x 16i8
5144         {3, MVT::v32i8, 14}, //(load 96i8 and) deinterleave into 3 x 32i8
5145         {3, MVT::v64i8, 22}, //(load 96i8 and) deinterleave into 3 x 32i8
5146     };
5147 
5148     if (const auto *Entry =
5149             CostTableLookup(AVX512InterleavedLoadTbl, Factor, VT))
5150       return NumOfMemOps * MemOpCost + Entry->Cost;
5151     //If an entry does not exist, fallback to the default implementation.
5152 
5153     // Kind of shuffle depends on number of loaded values.
5154     // If we load the entire data in one register, we can use a 1-src shuffle.
5155     // Otherwise, we'll merge 2 sources in each operation.
5156     TTI::ShuffleKind ShuffleKind =
5157         (NumOfMemOps > 1) ? TTI::SK_PermuteTwoSrc : TTI::SK_PermuteSingleSrc;
5158 
5159     InstructionCost ShuffleCost =
5160         getShuffleCost(ShuffleKind, SingleMemOpTy, None, 0, nullptr);
5161 
5162     unsigned NumOfLoadsInInterleaveGrp =
5163         Indices.size() ? Indices.size() : Factor;
5164     auto *ResultTy = FixedVectorType::get(VecTy->getElementType(),
5165                                           VecTy->getNumElements() / Factor);
5166     InstructionCost NumOfResults =
5167         getTLI()->getTypeLegalizationCost(DL, ResultTy).first *
5168         NumOfLoadsInInterleaveGrp;
5169 
5170     // About a half of the loads may be folded in shuffles when we have only
5171     // one result. If we have more than one result, we do not fold loads at all.
5172     unsigned NumOfUnfoldedLoads =
5173         NumOfResults > 1 ? NumOfMemOps : NumOfMemOps / 2;
5174 
5175     // Get a number of shuffle operations per result.
5176     unsigned NumOfShufflesPerResult =
5177         std::max((unsigned)1, (unsigned)(NumOfMemOps - 1));
5178 
5179     // The SK_MergeTwoSrc shuffle clobbers one of src operands.
5180     // When we have more than one destination, we need additional instructions
5181     // to keep sources.
5182     InstructionCost NumOfMoves = 0;
5183     if (NumOfResults > 1 && ShuffleKind == TTI::SK_PermuteTwoSrc)
5184       NumOfMoves = NumOfResults * NumOfShufflesPerResult / 2;
5185 
5186     InstructionCost Cost = NumOfResults * NumOfShufflesPerResult * ShuffleCost +
5187                            NumOfUnfoldedLoads * MemOpCost + NumOfMoves;
5188 
5189     return Cost;
5190   }
5191 
5192   // Store.
5193   assert(Opcode == Instruction::Store &&
5194          "Expected Store Instruction at this  point");
5195   // X86InterleavedAccess support only the following interleaved-access group.
5196   static const CostTblEntry AVX512InterleavedStoreTbl[] = {
5197       {3, MVT::v16i8, 12}, // interleave 3 x 16i8 into 48i8 (and store)
5198       {3, MVT::v32i8, 14}, // interleave 3 x 32i8 into 96i8 (and store)
5199       {3, MVT::v64i8, 26}, // interleave 3 x 64i8 into 96i8 (and store)
5200 
5201       {4, MVT::v8i8, 10},  // interleave 4 x 8i8  into 32i8  (and store)
5202       {4, MVT::v16i8, 11}, // interleave 4 x 16i8 into 64i8  (and store)
5203       {4, MVT::v32i8, 14}, // interleave 4 x 32i8 into 128i8 (and store)
5204       {4, MVT::v64i8, 24}  // interleave 4 x 32i8 into 256i8 (and store)
5205   };
5206 
5207   if (const auto *Entry =
5208           CostTableLookup(AVX512InterleavedStoreTbl, Factor, VT))
5209     return NumOfMemOps * MemOpCost + Entry->Cost;
5210   //If an entry does not exist, fallback to the default implementation.
5211 
5212   // There is no strided stores meanwhile. And store can't be folded in
5213   // shuffle.
5214   unsigned NumOfSources = Factor; // The number of values to be merged.
5215   InstructionCost ShuffleCost =
5216       getShuffleCost(TTI::SK_PermuteTwoSrc, SingleMemOpTy, None, 0, nullptr);
5217   unsigned NumOfShufflesPerStore = NumOfSources - 1;
5218 
5219   // The SK_MergeTwoSrc shuffle clobbers one of src operands.
5220   // We need additional instructions to keep sources.
5221   unsigned NumOfMoves = NumOfMemOps * NumOfShufflesPerStore / 2;
5222   InstructionCost Cost =
5223       NumOfMemOps * (MemOpCost + NumOfShufflesPerStore * ShuffleCost) +
5224       NumOfMoves;
5225   return Cost;
5226 }
5227 
5228 InstructionCost X86TTIImpl::getInterleavedMemoryOpCost(
5229     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
5230     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
5231     bool UseMaskForCond, bool UseMaskForGaps) {
5232   auto isSupportedOnAVX512 = [&](Type *VecTy, bool HasBW) {
5233     Type *EltTy = cast<VectorType>(VecTy)->getElementType();
5234     if (EltTy->isFloatTy() || EltTy->isDoubleTy() || EltTy->isIntegerTy(64) ||
5235         EltTy->isIntegerTy(32) || EltTy->isPointerTy())
5236       return true;
5237     if (EltTy->isIntegerTy(16) || EltTy->isIntegerTy(8) ||
5238         (!ST->useSoftFloat() && ST->hasFP16() && EltTy->isHalfTy()))
5239       return HasBW;
5240     return false;
5241   };
5242   if (ST->hasAVX512() && isSupportedOnAVX512(VecTy, ST->hasBWI()))
5243     return getInterleavedMemoryOpCostAVX512(
5244         Opcode, cast<FixedVectorType>(VecTy), Factor, Indices, Alignment,
5245         AddressSpace, CostKind, UseMaskForCond, UseMaskForGaps);
5246   if (ST->hasAVX2())
5247     return getInterleavedMemoryOpCostAVX2(
5248         Opcode, cast<FixedVectorType>(VecTy), Factor, Indices, Alignment,
5249         AddressSpace, CostKind, UseMaskForCond, UseMaskForGaps);
5250 
5251   return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
5252                                            Alignment, AddressSpace, CostKind,
5253                                            UseMaskForCond, UseMaskForGaps);
5254 }
5255