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