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