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