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     { ISD::TRUNCATE,  MVT::v4i8,    MVT::v4i64,  2 }, // vpmovqb
1688     { ISD::TRUNCATE,  MVT::v4i16,   MVT::v4i64,  2 }, // vpmovqw
1689     { ISD::TRUNCATE,  MVT::v8i8,    MVT::v8i32,  2 }, // vpmovwb
1690 
1691     // sign extend is vpcmpeq+maskedmove+vpmovdw+vpacksswb
1692     // zero extend is vpcmpeq+maskedmove+vpmovdw+vpsrlw+vpackuswb
1693     { ISD::SIGN_EXTEND, MVT::v2i8,   MVT::v2i1,   5 },
1694     { ISD::ZERO_EXTEND, MVT::v2i8,   MVT::v2i1,   6 },
1695     { ISD::SIGN_EXTEND, MVT::v4i8,   MVT::v4i1,   5 },
1696     { ISD::ZERO_EXTEND, MVT::v4i8,   MVT::v4i1,   6 },
1697     { ISD::SIGN_EXTEND, MVT::v8i8,   MVT::v8i1,   5 },
1698     { ISD::ZERO_EXTEND, MVT::v8i8,   MVT::v8i1,   6 },
1699     { ISD::SIGN_EXTEND, MVT::v16i8,  MVT::v16i1, 10 },
1700     { ISD::ZERO_EXTEND, MVT::v16i8,  MVT::v16i1, 12 },
1701 
1702     // sign extend is vpcmpeq+maskedmove+vpmovdw
1703     // zero extend is vpcmpeq+maskedmove+vpmovdw+vpsrlw
1704     { ISD::SIGN_EXTEND, MVT::v2i16,  MVT::v2i1,   4 },
1705     { ISD::ZERO_EXTEND, MVT::v2i16,  MVT::v2i1,   5 },
1706     { ISD::SIGN_EXTEND, MVT::v4i16,  MVT::v4i1,   4 },
1707     { ISD::ZERO_EXTEND, MVT::v4i16,  MVT::v4i1,   5 },
1708     { ISD::SIGN_EXTEND, MVT::v8i16,  MVT::v8i1,   4 },
1709     { ISD::ZERO_EXTEND, MVT::v8i16,  MVT::v8i1,   5 },
1710     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i1, 10 },
1711     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i1, 12 },
1712 
1713     { ISD::SIGN_EXTEND, MVT::v2i32,  MVT::v2i1,   1 }, // vpternlogd
1714     { ISD::ZERO_EXTEND, MVT::v2i32,  MVT::v2i1,   2 }, // vpternlogd+psrld
1715     { ISD::SIGN_EXTEND, MVT::v4i32,  MVT::v4i1,   1 }, // vpternlogd
1716     { ISD::ZERO_EXTEND, MVT::v4i32,  MVT::v4i1,   2 }, // vpternlogd+psrld
1717     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i1,   1 }, // vpternlogd
1718     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i1,   2 }, // vpternlogd+psrld
1719     { ISD::SIGN_EXTEND, MVT::v2i64,  MVT::v2i1,   1 }, // vpternlogq
1720     { ISD::ZERO_EXTEND, MVT::v2i64,  MVT::v2i1,   2 }, // vpternlogq+psrlq
1721     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i1,   1 }, // vpternlogq
1722     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i1,   2 }, // vpternlogq+psrlq
1723 
1724     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i8,   2 },
1725     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i8,   2 },
1726     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i8,   2 },
1727     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i16,  5 },
1728     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i16,  2 },
1729     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i16,  2 },
1730     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i32,  2 },
1731     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i32,  1 },
1732     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i32,  1 },
1733     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i32,  1 },
1734     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i32,  1 },
1735     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i64,  5 },
1736     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i64,  5 },
1737     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i64,  5 },
1738 
1739     { ISD::UINT_TO_FP,  MVT::f32,    MVT::i64,    1 },
1740     { ISD::UINT_TO_FP,  MVT::f64,    MVT::i64,    1 },
1741 
1742     { ISD::FP_TO_SINT,  MVT::v8i8,   MVT::v8f32,  3 },
1743     { ISD::FP_TO_UINT,  MVT::v8i8,   MVT::v8f32,  3 },
1744 
1745     { ISD::FP_TO_UINT,  MVT::i64,    MVT::f32,    1 },
1746     { ISD::FP_TO_UINT,  MVT::i64,    MVT::f64,    1 },
1747 
1748     { ISD::FP_TO_UINT,  MVT::v2i32,  MVT::v2f32,  1 },
1749     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v4f32,  1 },
1750     { ISD::FP_TO_UINT,  MVT::v2i32,  MVT::v2f64,  1 },
1751     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v4f64,  1 },
1752     { ISD::FP_TO_UINT,  MVT::v8i32,  MVT::v8f32,  1 },
1753   };
1754 
1755   static const TypeConversionCostTblEntry AVX2ConversionTbl[] = {
1756     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i1,   3 },
1757     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i1,   3 },
1758     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i1,   3 },
1759     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i1,   3 },
1760     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i8,   1 },
1761     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i8,   1 },
1762     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i8,   1 },
1763     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i8,   1 },
1764     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i1,  1 },
1765     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i1,  1 },
1766     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8,  1 },
1767     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8,  1 },
1768     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i16,  1 },
1769     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i16,  1 },
1770     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16,  1 },
1771     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16,  1 },
1772     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i32,  1 },
1773     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i32,  1 },
1774     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i16, 3 },
1775     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i16, 3 },
1776 
1777     { ISD::TRUNCATE,    MVT::v4i32,  MVT::v4i64,  2 },
1778     { ISD::TRUNCATE,    MVT::v8i1,   MVT::v8i32,  2 },
1779     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v8i32,  2 },
1780 
1781     { ISD::FP_EXTEND,   MVT::v8f64,  MVT::v8f32,  3 },
1782     { ISD::FP_ROUND,    MVT::v8f32,  MVT::v8f64,  3 },
1783 
1784     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i32,  8 },
1785   };
1786 
1787   static const TypeConversionCostTblEntry AVXConversionTbl[] = {
1788     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i1,  6 },
1789     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i1,  4 },
1790     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i1,  7 },
1791     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i1,  4 },
1792     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i8,  4 },
1793     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i8,  4 },
1794     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i8,  4 },
1795     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i8,  4 },
1796     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i1, 4 },
1797     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i1, 4 },
1798     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 4 },
1799     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 4 },
1800     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i16, 4 },
1801     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i16, 3 },
1802     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16, 4 },
1803     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16, 4 },
1804     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i32, 4 },
1805     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i32, 4 },
1806 
1807     { ISD::TRUNCATE,    MVT::v4i1,  MVT::v4i64,  4 },
1808     { ISD::TRUNCATE,    MVT::v8i1,  MVT::v8i32,  5 },
1809     { ISD::TRUNCATE,    MVT::v16i1, MVT::v16i16, 4 },
1810     { ISD::TRUNCATE,    MVT::v8i1,  MVT::v8i64,  9 },
1811     { ISD::TRUNCATE,    MVT::v16i1, MVT::v16i64, 11 },
1812 
1813     { ISD::TRUNCATE,    MVT::v16i8, MVT::v16i16, 4 },
1814     { ISD::TRUNCATE,    MVT::v8i8,  MVT::v8i32,  4 },
1815     { ISD::TRUNCATE,    MVT::v8i16, MVT::v8i32,  5 },
1816     { ISD::TRUNCATE,    MVT::v4i8,  MVT::v4i64,  4 },
1817     { ISD::TRUNCATE,    MVT::v4i16, MVT::v4i64,  4 },
1818     { ISD::TRUNCATE,    MVT::v4i32, MVT::v4i64,  2 },
1819     { ISD::TRUNCATE,    MVT::v8i8,  MVT::v8i64, 11 },
1820     { ISD::TRUNCATE,    MVT::v8i16, MVT::v8i64,  9 },
1821     { ISD::TRUNCATE,    MVT::v8i32, MVT::v8i64,  3 },
1822     { ISD::TRUNCATE,    MVT::v16i8, MVT::v16i64, 11 },
1823 
1824     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i1,  3 },
1825     { ISD::SINT_TO_FP,  MVT::v4f64, MVT::v4i1,  3 },
1826     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i1,  8 },
1827     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i8,  3 },
1828     { ISD::SINT_TO_FP,  MVT::v4f64, MVT::v4i8,  3 },
1829     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i8,  8 },
1830     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i16, 3 },
1831     { ISD::SINT_TO_FP,  MVT::v4f64, MVT::v4i16, 3 },
1832     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i16, 5 },
1833     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i32, 1 },
1834     { ISD::SINT_TO_FP,  MVT::v4f64, MVT::v4i32, 1 },
1835     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i32, 1 },
1836 
1837     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i1,  7 },
1838     { ISD::UINT_TO_FP,  MVT::v4f64, MVT::v4i1,  7 },
1839     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i1,  6 },
1840     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i8,  2 },
1841     { ISD::UINT_TO_FP,  MVT::v4f64, MVT::v4i8,  2 },
1842     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i8,  5 },
1843     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i16, 2 },
1844     { ISD::UINT_TO_FP,  MVT::v4f64, MVT::v4i16, 2 },
1845     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i16, 5 },
1846     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i32, 6 },
1847     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i32, 6 },
1848     { ISD::UINT_TO_FP,  MVT::v4f64, MVT::v4i32, 6 },
1849     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i32, 9 },
1850     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i64, 5 },
1851     { ISD::UINT_TO_FP,  MVT::v4f64, MVT::v4i64, 6 },
1852     // The generic code to compute the scalar overhead is currently broken.
1853     // Workaround this limitation by estimating the scalarization overhead
1854     // here. We have roughly 10 instructions per scalar element.
1855     // Multiply that by the vector width.
1856     // FIXME: remove that when PR19268 is fixed.
1857     { ISD::SINT_TO_FP,  MVT::v4f64, MVT::v4i64, 13 },
1858     { ISD::SINT_TO_FP,  MVT::v4f64, MVT::v4i64, 13 },
1859 
1860     { ISD::FP_TO_SINT,  MVT::v8i8,  MVT::v8f32, 4 },
1861     { ISD::FP_TO_SINT,  MVT::v4i8,  MVT::v4f64, 3 },
1862     { ISD::FP_TO_SINT,  MVT::v4i16, MVT::v4f64, 2 },
1863     { ISD::FP_TO_SINT,  MVT::v8i16, MVT::v8f32, 3 },
1864 
1865     { ISD::FP_TO_UINT,  MVT::v4i8,  MVT::v4f64, 3 },
1866     { ISD::FP_TO_UINT,  MVT::v4i16, MVT::v4f64, 2 },
1867     { ISD::FP_TO_UINT,  MVT::v8i8,  MVT::v8f32, 4 },
1868     { ISD::FP_TO_UINT,  MVT::v8i16, MVT::v8f32, 3 },
1869     // This node is expanded into scalarized operations but BasicTTI is overly
1870     // optimistic estimating its cost.  It computes 3 per element (one
1871     // vector-extract, one scalar conversion and one vector-insert).  The
1872     // problem is that the inserts form a read-modify-write chain so latency
1873     // should be factored in too.  Inflating the cost per element by 1.
1874     { ISD::FP_TO_UINT,  MVT::v8i32, MVT::v8f32, 8*4 },
1875     { ISD::FP_TO_UINT,  MVT::v4i32, MVT::v4f64, 4*4 },
1876 
1877     { ISD::FP_EXTEND,   MVT::v4f64,  MVT::v4f32,  1 },
1878     { ISD::FP_ROUND,    MVT::v4f32,  MVT::v4f64,  1 },
1879   };
1880 
1881   static const TypeConversionCostTblEntry SSE41ConversionTbl[] = {
1882     { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i8,    2 },
1883     { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i8,    2 },
1884     { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16,   2 },
1885     { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16,   2 },
1886     { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32,   2 },
1887     { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32,   2 },
1888 
1889     { ISD::ZERO_EXTEND, MVT::v4i16,  MVT::v4i8,   1 },
1890     { ISD::SIGN_EXTEND, MVT::v4i16,  MVT::v4i8,   2 },
1891     { ISD::ZERO_EXTEND, MVT::v4i32,  MVT::v4i8,   1 },
1892     { ISD::SIGN_EXTEND, MVT::v4i32,  MVT::v4i8,   1 },
1893     { ISD::ZERO_EXTEND, MVT::v8i16,  MVT::v8i8,   1 },
1894     { ISD::SIGN_EXTEND, MVT::v8i16,  MVT::v8i8,   1 },
1895     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i8,   2 },
1896     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i8,   2 },
1897     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8,  2 },
1898     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8,  2 },
1899     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8,  4 },
1900     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8,  4 },
1901     { ISD::ZERO_EXTEND, MVT::v4i32,  MVT::v4i16,  1 },
1902     { ISD::SIGN_EXTEND, MVT::v4i32,  MVT::v4i16,  1 },
1903     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16,  2 },
1904     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16,  2 },
1905     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i16, 4 },
1906     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i16, 4 },
1907 
1908     // These truncates end up widening elements.
1909     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i8,   1 }, // PMOVXZBQ
1910     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i16,  1 }, // PMOVXZWQ
1911     { ISD::TRUNCATE,    MVT::v4i1,   MVT::v4i8,   1 }, // PMOVXZBD
1912 
1913     { ISD::TRUNCATE,    MVT::v2i8,   MVT::v2i16,  1 },
1914     { ISD::TRUNCATE,    MVT::v4i8,   MVT::v4i16,  1 },
1915     { ISD::TRUNCATE,    MVT::v8i8,   MVT::v8i16,  1 },
1916     { ISD::TRUNCATE,    MVT::v4i8,   MVT::v4i32,  1 },
1917     { ISD::TRUNCATE,    MVT::v4i16,  MVT::v4i32,  1 },
1918     { ISD::TRUNCATE,    MVT::v8i8,   MVT::v8i32,  3 },
1919     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v8i32,  3 },
1920     { ISD::TRUNCATE,    MVT::v16i16, MVT::v16i32, 6 },
1921     { ISD::TRUNCATE,    MVT::v2i8,   MVT::v2i64,  1 }, // PSHUFB
1922 
1923     { ISD::UINT_TO_FP,  MVT::f32,    MVT::i64,    4 },
1924     { ISD::UINT_TO_FP,  MVT::f64,    MVT::i64,    4 },
1925 
1926     { ISD::FP_TO_SINT,  MVT::v2i8,   MVT::v2f32,  3 },
1927     { ISD::FP_TO_SINT,  MVT::v2i8,   MVT::v2f64,  3 },
1928 
1929     { ISD::FP_TO_UINT,  MVT::v2i8,   MVT::v2f32,  3 },
1930     { ISD::FP_TO_UINT,  MVT::v2i8,   MVT::v2f64,  3 },
1931     { ISD::FP_TO_UINT,  MVT::v4i16,  MVT::v4f32,  2 },
1932   };
1933 
1934   static const TypeConversionCostTblEntry SSE2ConversionTbl[] = {
1935     // These are somewhat magic numbers justified by looking at the output of
1936     // Intel's IACA, running some kernels and making sure when we take
1937     // legalization into account the throughput will be overestimated.
1938     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v16i8, 8 },
1939     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v16i8, 16*10 },
1940     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v8i16, 15 },
1941     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v8i16, 8*10 },
1942     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 5 },
1943     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v4i32, 2*10 },
1944     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2*10 },
1945     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v2i64, 15 },
1946     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i64, 2*10 },
1947 
1948     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v16i8, 16*10 },
1949     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v16i8, 8 },
1950     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v8i16, 15 },
1951     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v8i16, 8*10 },
1952     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v4i32, 4*10 },
1953     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 8 },
1954     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 6 },
1955     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v2i64, 15 },
1956 
1957     { ISD::FP_TO_SINT,  MVT::v2i8,   MVT::v2f32,  4 },
1958     { ISD::FP_TO_SINT,  MVT::v2i16,  MVT::v2f32,  2 },
1959     { ISD::FP_TO_SINT,  MVT::v4i8,   MVT::v4f32,  3 },
1960     { ISD::FP_TO_SINT,  MVT::v4i16,  MVT::v4f32,  2 },
1961     { ISD::FP_TO_SINT,  MVT::v2i16,  MVT::v2f64,  2 },
1962     { ISD::FP_TO_SINT,  MVT::v2i8,   MVT::v2f64,  4 },
1963 
1964     { ISD::FP_TO_SINT,  MVT::v2i32,  MVT::v2f64,  1 },
1965 
1966     { ISD::UINT_TO_FP,  MVT::f32,    MVT::i64,    6 },
1967     { ISD::UINT_TO_FP,  MVT::f64,    MVT::i64,    6 },
1968 
1969     { ISD::FP_TO_UINT,  MVT::i64,    MVT::f32,    4 },
1970     { ISD::FP_TO_UINT,  MVT::i64,    MVT::f64,    4 },
1971     { ISD::FP_TO_UINT,  MVT::v2i8,   MVT::v2f32,  4 },
1972     { ISD::FP_TO_UINT,  MVT::v2i8,   MVT::v2f64,  4 },
1973     { ISD::FP_TO_UINT,  MVT::v4i8,   MVT::v4f32,  3 },
1974     { ISD::FP_TO_UINT,  MVT::v2i16,  MVT::v2f32,  2 },
1975     { ISD::FP_TO_UINT,  MVT::v2i16,  MVT::v2f64,  2 },
1976     { ISD::FP_TO_UINT,  MVT::v4i16,  MVT::v4f32,  4 },
1977 
1978     { ISD::ZERO_EXTEND, MVT::v4i16,  MVT::v4i8,   1 },
1979     { ISD::SIGN_EXTEND, MVT::v4i16,  MVT::v4i8,   6 },
1980     { ISD::ZERO_EXTEND, MVT::v4i32,  MVT::v4i8,   2 },
1981     { ISD::SIGN_EXTEND, MVT::v4i32,  MVT::v4i8,   3 },
1982     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i8,   4 },
1983     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i8,   8 },
1984     { ISD::ZERO_EXTEND, MVT::v8i16,  MVT::v8i8,   1 },
1985     { ISD::SIGN_EXTEND, MVT::v8i16,  MVT::v8i8,   2 },
1986     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i8,   6 },
1987     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i8,   6 },
1988     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8,  3 },
1989     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8,  4 },
1990     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8,  9 },
1991     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8,  12 },
1992     { ISD::ZERO_EXTEND, MVT::v4i32,  MVT::v4i16,  1 },
1993     { ISD::SIGN_EXTEND, MVT::v4i32,  MVT::v4i16,  2 },
1994     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i16,  3 },
1995     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i16,  10 },
1996     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16,  3 },
1997     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16,  4 },
1998     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i16, 6 },
1999     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i16, 8 },
2000     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i32,  3 },
2001     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i32,  5 },
2002 
2003     // These truncates are really widening elements.
2004     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i32,  1 }, // PSHUFD
2005     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i16,  2 }, // PUNPCKLWD+DQ
2006     { ISD::TRUNCATE,    MVT::v2i1,   MVT::v2i8,   3 }, // PUNPCKLBW+WD+PSHUFD
2007     { ISD::TRUNCATE,    MVT::v4i1,   MVT::v4i16,  1 }, // PUNPCKLWD
2008     { ISD::TRUNCATE,    MVT::v4i1,   MVT::v4i8,   2 }, // PUNPCKLBW+WD
2009     { ISD::TRUNCATE,    MVT::v8i1,   MVT::v8i8,   1 }, // PUNPCKLBW
2010 
2011     { ISD::TRUNCATE,    MVT::v2i8,   MVT::v2i16,  2 }, // PAND+PACKUSWB
2012     { ISD::TRUNCATE,    MVT::v4i8,   MVT::v4i16,  2 }, // PAND+PACKUSWB
2013     { ISD::TRUNCATE,    MVT::v8i8,   MVT::v8i16,  2 }, // PAND+PACKUSWB
2014     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v16i16, 3 },
2015     { ISD::TRUNCATE,    MVT::v2i8,   MVT::v2i32,  3 }, // PAND+2*PACKUSWB
2016     { ISD::TRUNCATE,    MVT::v2i16,  MVT::v2i32,  1 },
2017     { ISD::TRUNCATE,    MVT::v4i8,   MVT::v4i32,  3 },
2018     { ISD::TRUNCATE,    MVT::v4i16,  MVT::v4i32,  3 },
2019     { ISD::TRUNCATE,    MVT::v8i8,   MVT::v8i32,  4 },
2020     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v16i32, 7 },
2021     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v8i32,  5 },
2022     { ISD::TRUNCATE,    MVT::v16i16, MVT::v16i32, 10 },
2023     { ISD::TRUNCATE,    MVT::v2i8,   MVT::v2i64,  4 }, // PAND+3*PACKUSWB
2024     { ISD::TRUNCATE,    MVT::v2i16,  MVT::v2i64,  2 }, // PSHUFD+PSHUFLW
2025     { ISD::TRUNCATE,    MVT::v2i32,  MVT::v2i64,  1 }, // PSHUFD
2026   };
2027 
2028   std::pair<InstructionCost, MVT> LTSrc = TLI->getTypeLegalizationCost(DL, Src);
2029   std::pair<InstructionCost, MVT> LTDest =
2030       TLI->getTypeLegalizationCost(DL, Dst);
2031 
2032   if (ST->hasSSE2() && !ST->hasAVX()) {
2033     if (const auto *Entry = ConvertCostTableLookup(SSE2ConversionTbl, ISD,
2034                                                    LTDest.second, LTSrc.second))
2035       return AdjustCost(LTSrc.first * Entry->Cost);
2036   }
2037 
2038   EVT SrcTy = TLI->getValueType(DL, Src);
2039   EVT DstTy = TLI->getValueType(DL, Dst);
2040 
2041   // The function getSimpleVT only handles simple value types.
2042   if (!SrcTy.isSimple() || !DstTy.isSimple())
2043     return AdjustCost(BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind));
2044 
2045   MVT SimpleSrcTy = SrcTy.getSimpleVT();
2046   MVT SimpleDstTy = DstTy.getSimpleVT();
2047 
2048   if (ST->useAVX512Regs()) {
2049     if (ST->hasBWI())
2050       if (const auto *Entry = ConvertCostTableLookup(AVX512BWConversionTbl, ISD,
2051                                                      SimpleDstTy, SimpleSrcTy))
2052         return AdjustCost(Entry->Cost);
2053 
2054     if (ST->hasDQI())
2055       if (const auto *Entry = ConvertCostTableLookup(AVX512DQConversionTbl, ISD,
2056                                                      SimpleDstTy, SimpleSrcTy))
2057         return AdjustCost(Entry->Cost);
2058 
2059     if (ST->hasAVX512())
2060       if (const auto *Entry = ConvertCostTableLookup(AVX512FConversionTbl, ISD,
2061                                                      SimpleDstTy, SimpleSrcTy))
2062         return AdjustCost(Entry->Cost);
2063   }
2064 
2065   if (ST->hasBWI())
2066     if (const auto *Entry = ConvertCostTableLookup(AVX512BWVLConversionTbl, ISD,
2067                                                    SimpleDstTy, SimpleSrcTy))
2068       return AdjustCost(Entry->Cost);
2069 
2070   if (ST->hasDQI())
2071     if (const auto *Entry = ConvertCostTableLookup(AVX512DQVLConversionTbl, ISD,
2072                                                    SimpleDstTy, SimpleSrcTy))
2073       return AdjustCost(Entry->Cost);
2074 
2075   if (ST->hasAVX512())
2076     if (const auto *Entry = ConvertCostTableLookup(AVX512VLConversionTbl, ISD,
2077                                                    SimpleDstTy, SimpleSrcTy))
2078       return AdjustCost(Entry->Cost);
2079 
2080   if (ST->hasAVX2()) {
2081     if (const auto *Entry = ConvertCostTableLookup(AVX2ConversionTbl, ISD,
2082                                                    SimpleDstTy, SimpleSrcTy))
2083       return AdjustCost(Entry->Cost);
2084   }
2085 
2086   if (ST->hasAVX()) {
2087     if (const auto *Entry = ConvertCostTableLookup(AVXConversionTbl, ISD,
2088                                                    SimpleDstTy, SimpleSrcTy))
2089       return AdjustCost(Entry->Cost);
2090   }
2091 
2092   if (ST->hasSSE41()) {
2093     if (const auto *Entry = ConvertCostTableLookup(SSE41ConversionTbl, ISD,
2094                                                    SimpleDstTy, SimpleSrcTy))
2095       return AdjustCost(Entry->Cost);
2096   }
2097 
2098   if (ST->hasSSE2()) {
2099     if (const auto *Entry = ConvertCostTableLookup(SSE2ConversionTbl, ISD,
2100                                                    SimpleDstTy, SimpleSrcTy))
2101       return AdjustCost(Entry->Cost);
2102   }
2103 
2104   return AdjustCost(
2105       BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
2106 }
2107 
2108 InstructionCost X86TTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
2109                                                Type *CondTy,
2110                                                CmpInst::Predicate VecPred,
2111                                                TTI::TargetCostKind CostKind,
2112                                                const Instruction *I) {
2113   // TODO: Handle other cost kinds.
2114   if (CostKind != TTI::TCK_RecipThroughput)
2115     return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind,
2116                                      I);
2117 
2118   // Legalize the type.
2119   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
2120 
2121   MVT MTy = LT.second;
2122 
2123   int ISD = TLI->InstructionOpcodeToISD(Opcode);
2124   assert(ISD && "Invalid opcode");
2125 
2126   unsigned ExtraCost = 0;
2127   if (I && (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp)) {
2128     // Some vector comparison predicates cost extra instructions.
2129     if (MTy.isVector() &&
2130         !((ST->hasXOP() && (!ST->hasAVX2() || MTy.is128BitVector())) ||
2131           (ST->hasAVX512() && 32 <= MTy.getScalarSizeInBits()) ||
2132           ST->hasBWI())) {
2133       switch (cast<CmpInst>(I)->getPredicate()) {
2134       case CmpInst::Predicate::ICMP_NE:
2135         // xor(cmpeq(x,y),-1)
2136         ExtraCost = 1;
2137         break;
2138       case CmpInst::Predicate::ICMP_SGE:
2139       case CmpInst::Predicate::ICMP_SLE:
2140         // xor(cmpgt(x,y),-1)
2141         ExtraCost = 1;
2142         break;
2143       case CmpInst::Predicate::ICMP_ULT:
2144       case CmpInst::Predicate::ICMP_UGT:
2145         // cmpgt(xor(x,signbit),xor(y,signbit))
2146         // xor(cmpeq(pmaxu(x,y),x),-1)
2147         ExtraCost = 2;
2148         break;
2149       case CmpInst::Predicate::ICMP_ULE:
2150       case CmpInst::Predicate::ICMP_UGE:
2151         if ((ST->hasSSE41() && MTy.getScalarSizeInBits() == 32) ||
2152             (ST->hasSSE2() && MTy.getScalarSizeInBits() < 32)) {
2153           // cmpeq(psubus(x,y),0)
2154           // cmpeq(pminu(x,y),x)
2155           ExtraCost = 1;
2156         } else {
2157           // xor(cmpgt(xor(x,signbit),xor(y,signbit)),-1)
2158           ExtraCost = 3;
2159         }
2160         break;
2161       default:
2162         break;
2163       }
2164     }
2165   }
2166 
2167   static const CostTblEntry SLMCostTbl[] = {
2168     // slm pcmpeq/pcmpgt throughput is 2
2169     { ISD::SETCC,   MVT::v2i64,   2 },
2170   };
2171 
2172   static const CostTblEntry AVX512BWCostTbl[] = {
2173     { ISD::SETCC,   MVT::v32i16,  1 },
2174     { ISD::SETCC,   MVT::v64i8,   1 },
2175 
2176     { ISD::SELECT,  MVT::v32i16,  1 },
2177     { ISD::SELECT,  MVT::v64i8,   1 },
2178   };
2179 
2180   static const CostTblEntry AVX512CostTbl[] = {
2181     { ISD::SETCC,   MVT::v8i64,   1 },
2182     { ISD::SETCC,   MVT::v16i32,  1 },
2183     { ISD::SETCC,   MVT::v8f64,   1 },
2184     { ISD::SETCC,   MVT::v16f32,  1 },
2185 
2186     { ISD::SELECT,  MVT::v8i64,   1 },
2187     { ISD::SELECT,  MVT::v16i32,  1 },
2188     { ISD::SELECT,  MVT::v8f64,   1 },
2189     { ISD::SELECT,  MVT::v16f32,  1 },
2190 
2191     { ISD::SETCC,   MVT::v32i16,  2 }, // FIXME: should probably be 4
2192     { ISD::SETCC,   MVT::v64i8,   2 }, // FIXME: should probably be 4
2193 
2194     { ISD::SELECT,  MVT::v32i16,  2 }, // FIXME: should be 3
2195     { ISD::SELECT,  MVT::v64i8,   2 }, // FIXME: should be 3
2196   };
2197 
2198   static const CostTblEntry AVX2CostTbl[] = {
2199     { ISD::SETCC,   MVT::v4i64,   1 },
2200     { ISD::SETCC,   MVT::v8i32,   1 },
2201     { ISD::SETCC,   MVT::v16i16,  1 },
2202     { ISD::SETCC,   MVT::v32i8,   1 },
2203 
2204     { ISD::SELECT,  MVT::v4i64,   1 }, // pblendvb
2205     { ISD::SELECT,  MVT::v8i32,   1 }, // pblendvb
2206     { ISD::SELECT,  MVT::v16i16,  1 }, // pblendvb
2207     { ISD::SELECT,  MVT::v32i8,   1 }, // pblendvb
2208   };
2209 
2210   static const CostTblEntry AVX1CostTbl[] = {
2211     { ISD::SETCC,   MVT::v4f64,   1 },
2212     { ISD::SETCC,   MVT::v8f32,   1 },
2213     // AVX1 does not support 8-wide integer compare.
2214     { ISD::SETCC,   MVT::v4i64,   4 },
2215     { ISD::SETCC,   MVT::v8i32,   4 },
2216     { ISD::SETCC,   MVT::v16i16,  4 },
2217     { ISD::SETCC,   MVT::v32i8,   4 },
2218 
2219     { ISD::SELECT,  MVT::v4f64,   1 }, // vblendvpd
2220     { ISD::SELECT,  MVT::v8f32,   1 }, // vblendvps
2221     { ISD::SELECT,  MVT::v4i64,   1 }, // vblendvpd
2222     { ISD::SELECT,  MVT::v8i32,   1 }, // vblendvps
2223     { ISD::SELECT,  MVT::v16i16,  3 }, // vandps + vandnps + vorps
2224     { ISD::SELECT,  MVT::v32i8,   3 }, // vandps + vandnps + vorps
2225   };
2226 
2227   static const CostTblEntry SSE42CostTbl[] = {
2228     { ISD::SETCC,   MVT::v2f64,   1 },
2229     { ISD::SETCC,   MVT::v4f32,   1 },
2230     { ISD::SETCC,   MVT::v2i64,   1 },
2231   };
2232 
2233   static const CostTblEntry SSE41CostTbl[] = {
2234     { ISD::SELECT,  MVT::v2f64,   1 }, // blendvpd
2235     { ISD::SELECT,  MVT::v4f32,   1 }, // blendvps
2236     { ISD::SELECT,  MVT::v2i64,   1 }, // pblendvb
2237     { ISD::SELECT,  MVT::v4i32,   1 }, // pblendvb
2238     { ISD::SELECT,  MVT::v8i16,   1 }, // pblendvb
2239     { ISD::SELECT,  MVT::v16i8,   1 }, // pblendvb
2240   };
2241 
2242   static const CostTblEntry SSE2CostTbl[] = {
2243     { ISD::SETCC,   MVT::v2f64,   2 },
2244     { ISD::SETCC,   MVT::f64,     1 },
2245     { ISD::SETCC,   MVT::v2i64,   8 },
2246     { ISD::SETCC,   MVT::v4i32,   1 },
2247     { ISD::SETCC,   MVT::v8i16,   1 },
2248     { ISD::SETCC,   MVT::v16i8,   1 },
2249 
2250     { ISD::SELECT,  MVT::v2f64,   3 }, // andpd + andnpd + orpd
2251     { ISD::SELECT,  MVT::v2i64,   3 }, // pand + pandn + por
2252     { ISD::SELECT,  MVT::v4i32,   3 }, // pand + pandn + por
2253     { ISD::SELECT,  MVT::v8i16,   3 }, // pand + pandn + por
2254     { ISD::SELECT,  MVT::v16i8,   3 }, // pand + pandn + por
2255   };
2256 
2257   static const CostTblEntry SSE1CostTbl[] = {
2258     { ISD::SETCC,   MVT::v4f32,   2 },
2259     { ISD::SETCC,   MVT::f32,     1 },
2260 
2261     { ISD::SELECT,  MVT::v4f32,   3 }, // andps + andnps + orps
2262   };
2263 
2264   if (ST->isSLM())
2265     if (const auto *Entry = CostTableLookup(SLMCostTbl, ISD, MTy))
2266       return LT.first * (ExtraCost + Entry->Cost);
2267 
2268   if (ST->hasBWI())
2269     if (const auto *Entry = CostTableLookup(AVX512BWCostTbl, ISD, MTy))
2270       return LT.first * (ExtraCost + Entry->Cost);
2271 
2272   if (ST->hasAVX512())
2273     if (const auto *Entry = CostTableLookup(AVX512CostTbl, ISD, MTy))
2274       return LT.first * (ExtraCost + Entry->Cost);
2275 
2276   if (ST->hasAVX2())
2277     if (const auto *Entry = CostTableLookup(AVX2CostTbl, ISD, MTy))
2278       return LT.first * (ExtraCost + Entry->Cost);
2279 
2280   if (ST->hasAVX())
2281     if (const auto *Entry = CostTableLookup(AVX1CostTbl, ISD, MTy))
2282       return LT.first * (ExtraCost + Entry->Cost);
2283 
2284   if (ST->hasSSE42())
2285     if (const auto *Entry = CostTableLookup(SSE42CostTbl, ISD, MTy))
2286       return LT.first * (ExtraCost + Entry->Cost);
2287 
2288   if (ST->hasSSE41())
2289     if (const auto *Entry = CostTableLookup(SSE41CostTbl, ISD, MTy))
2290       return LT.first * (ExtraCost + Entry->Cost);
2291 
2292   if (ST->hasSSE2())
2293     if (const auto *Entry = CostTableLookup(SSE2CostTbl, ISD, MTy))
2294       return LT.first * (ExtraCost + Entry->Cost);
2295 
2296   if (ST->hasSSE1())
2297     if (const auto *Entry = CostTableLookup(SSE1CostTbl, ISD, MTy))
2298       return LT.first * (ExtraCost + Entry->Cost);
2299 
2300   return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I);
2301 }
2302 
2303 unsigned X86TTIImpl::getAtomicMemIntrinsicMaxElementSize() const { return 16; }
2304 
2305 InstructionCost
2306 X86TTIImpl::getTypeBasedIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
2307                                            TTI::TargetCostKind CostKind) {
2308 
2309   // Costs should match the codegen from:
2310   // BITREVERSE: llvm\test\CodeGen\X86\vector-bitreverse.ll
2311   // BSWAP: llvm\test\CodeGen\X86\bswap-vector.ll
2312   // CTLZ: llvm\test\CodeGen\X86\vector-lzcnt-*.ll
2313   // CTPOP: llvm\test\CodeGen\X86\vector-popcnt-*.ll
2314   // CTTZ: llvm\test\CodeGen\X86\vector-tzcnt-*.ll
2315 
2316   // TODO: Overflow intrinsics (*ADDO, *SUBO, *MULO) with vector types are not
2317   //       specialized in these tables yet.
2318   static const CostTblEntry AVX512CDCostTbl[] = {
2319     { ISD::CTLZ,       MVT::v8i64,   1 },
2320     { ISD::CTLZ,       MVT::v16i32,  1 },
2321     { ISD::CTLZ,       MVT::v32i16,  8 },
2322     { ISD::CTLZ,       MVT::v64i8,  20 },
2323     { ISD::CTLZ,       MVT::v4i64,   1 },
2324     { ISD::CTLZ,       MVT::v8i32,   1 },
2325     { ISD::CTLZ,       MVT::v16i16,  4 },
2326     { ISD::CTLZ,       MVT::v32i8,  10 },
2327     { ISD::CTLZ,       MVT::v2i64,   1 },
2328     { ISD::CTLZ,       MVT::v4i32,   1 },
2329     { ISD::CTLZ,       MVT::v8i16,   4 },
2330     { ISD::CTLZ,       MVT::v16i8,   4 },
2331   };
2332   static const CostTblEntry AVX512BWCostTbl[] = {
2333     { ISD::ABS,        MVT::v32i16,  1 },
2334     { ISD::ABS,        MVT::v64i8,   1 },
2335     { ISD::BITREVERSE, MVT::v8i64,   5 },
2336     { ISD::BITREVERSE, MVT::v16i32,  5 },
2337     { ISD::BITREVERSE, MVT::v32i16,  5 },
2338     { ISD::BITREVERSE, MVT::v64i8,   5 },
2339     { ISD::CTLZ,       MVT::v8i64,  23 },
2340     { ISD::CTLZ,       MVT::v16i32, 22 },
2341     { ISD::CTLZ,       MVT::v32i16, 18 },
2342     { ISD::CTLZ,       MVT::v64i8,  17 },
2343     { ISD::CTPOP,      MVT::v8i64,   7 },
2344     { ISD::CTPOP,      MVT::v16i32, 11 },
2345     { ISD::CTPOP,      MVT::v32i16,  9 },
2346     { ISD::CTPOP,      MVT::v64i8,   6 },
2347     { ISD::CTTZ,       MVT::v8i64,  10 },
2348     { ISD::CTTZ,       MVT::v16i32, 14 },
2349     { ISD::CTTZ,       MVT::v32i16, 12 },
2350     { ISD::CTTZ,       MVT::v64i8,   9 },
2351     { ISD::SADDSAT,    MVT::v32i16,  1 },
2352     { ISD::SADDSAT,    MVT::v64i8,   1 },
2353     { ISD::SMAX,       MVT::v32i16,  1 },
2354     { ISD::SMAX,       MVT::v64i8,   1 },
2355     { ISD::SMIN,       MVT::v32i16,  1 },
2356     { ISD::SMIN,       MVT::v64i8,   1 },
2357     { ISD::SSUBSAT,    MVT::v32i16,  1 },
2358     { ISD::SSUBSAT,    MVT::v64i8,   1 },
2359     { ISD::UADDSAT,    MVT::v32i16,  1 },
2360     { ISD::UADDSAT,    MVT::v64i8,   1 },
2361     { ISD::UMAX,       MVT::v32i16,  1 },
2362     { ISD::UMAX,       MVT::v64i8,   1 },
2363     { ISD::UMIN,       MVT::v32i16,  1 },
2364     { ISD::UMIN,       MVT::v64i8,   1 },
2365     { ISD::USUBSAT,    MVT::v32i16,  1 },
2366     { ISD::USUBSAT,    MVT::v64i8,   1 },
2367   };
2368   static const CostTblEntry AVX512CostTbl[] = {
2369     { ISD::ABS,        MVT::v8i64,   1 },
2370     { ISD::ABS,        MVT::v16i32,  1 },
2371     { ISD::ABS,        MVT::v32i16,  2 }, // FIXME: include split
2372     { ISD::ABS,        MVT::v64i8,   2 }, // FIXME: include split
2373     { ISD::ABS,        MVT::v4i64,   1 },
2374     { ISD::ABS,        MVT::v2i64,   1 },
2375     { ISD::BITREVERSE, MVT::v8i64,  36 },
2376     { ISD::BITREVERSE, MVT::v16i32, 24 },
2377     { ISD::BITREVERSE, MVT::v32i16, 10 },
2378     { ISD::BITREVERSE, MVT::v64i8,  10 },
2379     { ISD::CTLZ,       MVT::v8i64,  29 },
2380     { ISD::CTLZ,       MVT::v16i32, 35 },
2381     { ISD::CTLZ,       MVT::v32i16, 28 },
2382     { ISD::CTLZ,       MVT::v64i8,  18 },
2383     { ISD::CTPOP,      MVT::v8i64,  16 },
2384     { ISD::CTPOP,      MVT::v16i32, 24 },
2385     { ISD::CTPOP,      MVT::v32i16, 18 },
2386     { ISD::CTPOP,      MVT::v64i8,  12 },
2387     { ISD::CTTZ,       MVT::v8i64,  20 },
2388     { ISD::CTTZ,       MVT::v16i32, 28 },
2389     { ISD::CTTZ,       MVT::v32i16, 24 },
2390     { ISD::CTTZ,       MVT::v64i8,  18 },
2391     { ISD::SMAX,       MVT::v8i64,   1 },
2392     { ISD::SMAX,       MVT::v16i32,  1 },
2393     { ISD::SMAX,       MVT::v32i16,  2 }, // FIXME: include split
2394     { ISD::SMAX,       MVT::v64i8,   2 }, // FIXME: include split
2395     { ISD::SMAX,       MVT::v4i64,   1 },
2396     { ISD::SMAX,       MVT::v2i64,   1 },
2397     { ISD::SMIN,       MVT::v8i64,   1 },
2398     { ISD::SMIN,       MVT::v16i32,  1 },
2399     { ISD::SMIN,       MVT::v32i16,  2 }, // FIXME: include split
2400     { ISD::SMIN,       MVT::v64i8,   2 }, // FIXME: include split
2401     { ISD::SMIN,       MVT::v4i64,   1 },
2402     { ISD::SMIN,       MVT::v2i64,   1 },
2403     { ISD::UMAX,       MVT::v8i64,   1 },
2404     { ISD::UMAX,       MVT::v16i32,  1 },
2405     { ISD::UMAX,       MVT::v32i16,  2 }, // FIXME: include split
2406     { ISD::UMAX,       MVT::v64i8,   2 }, // FIXME: include split
2407     { ISD::UMAX,       MVT::v4i64,   1 },
2408     { ISD::UMAX,       MVT::v2i64,   1 },
2409     { ISD::UMIN,       MVT::v8i64,   1 },
2410     { ISD::UMIN,       MVT::v16i32,  1 },
2411     { ISD::UMIN,       MVT::v32i16,  2 }, // FIXME: include split
2412     { ISD::UMIN,       MVT::v64i8,   2 }, // FIXME: include split
2413     { ISD::UMIN,       MVT::v4i64,   1 },
2414     { ISD::UMIN,       MVT::v2i64,   1 },
2415     { ISD::USUBSAT,    MVT::v16i32,  2 }, // pmaxud + psubd
2416     { ISD::USUBSAT,    MVT::v2i64,   2 }, // pmaxuq + psubq
2417     { ISD::USUBSAT,    MVT::v4i64,   2 }, // pmaxuq + psubq
2418     { ISD::USUBSAT,    MVT::v8i64,   2 }, // pmaxuq + psubq
2419     { ISD::UADDSAT,    MVT::v16i32,  3 }, // not + pminud + paddd
2420     { ISD::UADDSAT,    MVT::v2i64,   3 }, // not + pminuq + paddq
2421     { ISD::UADDSAT,    MVT::v4i64,   3 }, // not + pminuq + paddq
2422     { ISD::UADDSAT,    MVT::v8i64,   3 }, // not + pminuq + paddq
2423     { ISD::SADDSAT,    MVT::v32i16,  2 }, // FIXME: include split
2424     { ISD::SADDSAT,    MVT::v64i8,   2 }, // FIXME: include split
2425     { ISD::SSUBSAT,    MVT::v32i16,  2 }, // FIXME: include split
2426     { ISD::SSUBSAT,    MVT::v64i8,   2 }, // FIXME: include split
2427     { ISD::UADDSAT,    MVT::v32i16,  2 }, // FIXME: include split
2428     { ISD::UADDSAT,    MVT::v64i8,   2 }, // FIXME: include split
2429     { ISD::USUBSAT,    MVT::v32i16,  2 }, // FIXME: include split
2430     { ISD::USUBSAT,    MVT::v64i8,   2 }, // FIXME: include split
2431     { ISD::FMAXNUM,    MVT::f32,     2 },
2432     { ISD::FMAXNUM,    MVT::v4f32,   2 },
2433     { ISD::FMAXNUM,    MVT::v8f32,   2 },
2434     { ISD::FMAXNUM,    MVT::v16f32,  2 },
2435     { ISD::FMAXNUM,    MVT::f64,     2 },
2436     { ISD::FMAXNUM,    MVT::v2f64,   2 },
2437     { ISD::FMAXNUM,    MVT::v4f64,   2 },
2438     { ISD::FMAXNUM,    MVT::v8f64,   2 },
2439   };
2440   static const CostTblEntry XOPCostTbl[] = {
2441     { ISD::BITREVERSE, MVT::v4i64,   4 },
2442     { ISD::BITREVERSE, MVT::v8i32,   4 },
2443     { ISD::BITREVERSE, MVT::v16i16,  4 },
2444     { ISD::BITREVERSE, MVT::v32i8,   4 },
2445     { ISD::BITREVERSE, MVT::v2i64,   1 },
2446     { ISD::BITREVERSE, MVT::v4i32,   1 },
2447     { ISD::BITREVERSE, MVT::v8i16,   1 },
2448     { ISD::BITREVERSE, MVT::v16i8,   1 },
2449     { ISD::BITREVERSE, MVT::i64,     3 },
2450     { ISD::BITREVERSE, MVT::i32,     3 },
2451     { ISD::BITREVERSE, MVT::i16,     3 },
2452     { ISD::BITREVERSE, MVT::i8,      3 }
2453   };
2454   static const CostTblEntry AVX2CostTbl[] = {
2455     { ISD::ABS,        MVT::v4i64,   2 }, // VBLENDVPD(X,VPSUBQ(0,X),X)
2456     { ISD::ABS,        MVT::v8i32,   1 },
2457     { ISD::ABS,        MVT::v16i16,  1 },
2458     { ISD::ABS,        MVT::v32i8,   1 },
2459     { ISD::BITREVERSE, MVT::v4i64,   5 },
2460     { ISD::BITREVERSE, MVT::v8i32,   5 },
2461     { ISD::BITREVERSE, MVT::v16i16,  5 },
2462     { ISD::BITREVERSE, MVT::v32i8,   5 },
2463     { ISD::BSWAP,      MVT::v4i64,   1 },
2464     { ISD::BSWAP,      MVT::v8i32,   1 },
2465     { ISD::BSWAP,      MVT::v16i16,  1 },
2466     { ISD::CTLZ,       MVT::v4i64,  23 },
2467     { ISD::CTLZ,       MVT::v8i32,  18 },
2468     { ISD::CTLZ,       MVT::v16i16, 14 },
2469     { ISD::CTLZ,       MVT::v32i8,   9 },
2470     { ISD::CTPOP,      MVT::v4i64,   7 },
2471     { ISD::CTPOP,      MVT::v8i32,  11 },
2472     { ISD::CTPOP,      MVT::v16i16,  9 },
2473     { ISD::CTPOP,      MVT::v32i8,   6 },
2474     { ISD::CTTZ,       MVT::v4i64,  10 },
2475     { ISD::CTTZ,       MVT::v8i32,  14 },
2476     { ISD::CTTZ,       MVT::v16i16, 12 },
2477     { ISD::CTTZ,       MVT::v32i8,   9 },
2478     { ISD::SADDSAT,    MVT::v16i16,  1 },
2479     { ISD::SADDSAT,    MVT::v32i8,   1 },
2480     { ISD::SMAX,       MVT::v8i32,   1 },
2481     { ISD::SMAX,       MVT::v16i16,  1 },
2482     { ISD::SMAX,       MVT::v32i8,   1 },
2483     { ISD::SMIN,       MVT::v8i32,   1 },
2484     { ISD::SMIN,       MVT::v16i16,  1 },
2485     { ISD::SMIN,       MVT::v32i8,   1 },
2486     { ISD::SSUBSAT,    MVT::v16i16,  1 },
2487     { ISD::SSUBSAT,    MVT::v32i8,   1 },
2488     { ISD::UADDSAT,    MVT::v16i16,  1 },
2489     { ISD::UADDSAT,    MVT::v32i8,   1 },
2490     { ISD::UADDSAT,    MVT::v8i32,   3 }, // not + pminud + paddd
2491     { ISD::UMAX,       MVT::v8i32,   1 },
2492     { ISD::UMAX,       MVT::v16i16,  1 },
2493     { ISD::UMAX,       MVT::v32i8,   1 },
2494     { ISD::UMIN,       MVT::v8i32,   1 },
2495     { ISD::UMIN,       MVT::v16i16,  1 },
2496     { ISD::UMIN,       MVT::v32i8,   1 },
2497     { ISD::USUBSAT,    MVT::v16i16,  1 },
2498     { ISD::USUBSAT,    MVT::v32i8,   1 },
2499     { ISD::USUBSAT,    MVT::v8i32,   2 }, // pmaxud + psubd
2500     { ISD::FMAXNUM,    MVT::v8f32,   3 }, // MAXPS + CMPUNORDPS + BLENDVPS
2501     { ISD::FMAXNUM,    MVT::v4f64,   3 }, // MAXPD + CMPUNORDPD + BLENDVPD
2502     { ISD::FSQRT,      MVT::f32,     7 }, // Haswell from http://www.agner.org/
2503     { ISD::FSQRT,      MVT::v4f32,   7 }, // Haswell from http://www.agner.org/
2504     { ISD::FSQRT,      MVT::v8f32,  14 }, // Haswell from http://www.agner.org/
2505     { ISD::FSQRT,      MVT::f64,    14 }, // Haswell from http://www.agner.org/
2506     { ISD::FSQRT,      MVT::v2f64,  14 }, // Haswell from http://www.agner.org/
2507     { ISD::FSQRT,      MVT::v4f64,  28 }, // Haswell from http://www.agner.org/
2508   };
2509   static const CostTblEntry AVX1CostTbl[] = {
2510     { ISD::ABS,        MVT::v4i64,   5 }, // VBLENDVPD(X,VPSUBQ(0,X),X)
2511     { ISD::ABS,        MVT::v8i32,   3 },
2512     { ISD::ABS,        MVT::v16i16,  3 },
2513     { ISD::ABS,        MVT::v32i8,   3 },
2514     { ISD::BITREVERSE, MVT::v4i64,  12 }, // 2 x 128-bit Op + extract/insert
2515     { ISD::BITREVERSE, MVT::v8i32,  12 }, // 2 x 128-bit Op + extract/insert
2516     { ISD::BITREVERSE, MVT::v16i16, 12 }, // 2 x 128-bit Op + extract/insert
2517     { ISD::BITREVERSE, MVT::v32i8,  12 }, // 2 x 128-bit Op + extract/insert
2518     { ISD::BSWAP,      MVT::v4i64,   4 },
2519     { ISD::BSWAP,      MVT::v8i32,   4 },
2520     { ISD::BSWAP,      MVT::v16i16,  4 },
2521     { ISD::CTLZ,       MVT::v4i64,  48 }, // 2 x 128-bit Op + extract/insert
2522     { ISD::CTLZ,       MVT::v8i32,  38 }, // 2 x 128-bit Op + extract/insert
2523     { ISD::CTLZ,       MVT::v16i16, 30 }, // 2 x 128-bit Op + extract/insert
2524     { ISD::CTLZ,       MVT::v32i8,  20 }, // 2 x 128-bit Op + extract/insert
2525     { ISD::CTPOP,      MVT::v4i64,  16 }, // 2 x 128-bit Op + extract/insert
2526     { ISD::CTPOP,      MVT::v8i32,  24 }, // 2 x 128-bit Op + extract/insert
2527     { ISD::CTPOP,      MVT::v16i16, 20 }, // 2 x 128-bit Op + extract/insert
2528     { ISD::CTPOP,      MVT::v32i8,  14 }, // 2 x 128-bit Op + extract/insert
2529     { ISD::CTTZ,       MVT::v4i64,  22 }, // 2 x 128-bit Op + extract/insert
2530     { ISD::CTTZ,       MVT::v8i32,  30 }, // 2 x 128-bit Op + extract/insert
2531     { ISD::CTTZ,       MVT::v16i16, 26 }, // 2 x 128-bit Op + extract/insert
2532     { ISD::CTTZ,       MVT::v32i8,  20 }, // 2 x 128-bit Op + extract/insert
2533     { ISD::SADDSAT,    MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2534     { ISD::SADDSAT,    MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2535     { ISD::SMAX,       MVT::v8i32,   4 }, // 2 x 128-bit Op + extract/insert
2536     { ISD::SMAX,       MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2537     { ISD::SMAX,       MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2538     { ISD::SMIN,       MVT::v8i32,   4 }, // 2 x 128-bit Op + extract/insert
2539     { ISD::SMIN,       MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2540     { ISD::SMIN,       MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2541     { ISD::SSUBSAT,    MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2542     { ISD::SSUBSAT,    MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2543     { ISD::UADDSAT,    MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2544     { ISD::UADDSAT,    MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2545     { ISD::UADDSAT,    MVT::v8i32,   8 }, // 2 x 128-bit Op + extract/insert
2546     { ISD::UMAX,       MVT::v8i32,   4 }, // 2 x 128-bit Op + extract/insert
2547     { ISD::UMAX,       MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2548     { ISD::UMAX,       MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2549     { ISD::UMIN,       MVT::v8i32,   4 }, // 2 x 128-bit Op + extract/insert
2550     { ISD::UMIN,       MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2551     { ISD::UMIN,       MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2552     { ISD::USUBSAT,    MVT::v16i16,  4 }, // 2 x 128-bit Op + extract/insert
2553     { ISD::USUBSAT,    MVT::v32i8,   4 }, // 2 x 128-bit Op + extract/insert
2554     { ISD::USUBSAT,    MVT::v8i32,   6 }, // 2 x 128-bit Op + extract/insert
2555     { ISD::FMAXNUM,    MVT::f32,     3 }, // MAXSS + CMPUNORDSS + BLENDVPS
2556     { ISD::FMAXNUM,    MVT::v4f32,   3 }, // MAXPS + CMPUNORDPS + BLENDVPS
2557     { ISD::FMAXNUM,    MVT::v8f32,   5 }, // MAXPS + CMPUNORDPS + BLENDVPS + ?
2558     { ISD::FMAXNUM,    MVT::f64,     3 }, // MAXSD + CMPUNORDSD + BLENDVPD
2559     { ISD::FMAXNUM,    MVT::v2f64,   3 }, // MAXPD + CMPUNORDPD + BLENDVPD
2560     { ISD::FMAXNUM,    MVT::v4f64,   5 }, // MAXPD + CMPUNORDPD + BLENDVPD + ?
2561     { ISD::FSQRT,      MVT::f32,    14 }, // SNB from http://www.agner.org/
2562     { ISD::FSQRT,      MVT::v4f32,  14 }, // SNB from http://www.agner.org/
2563     { ISD::FSQRT,      MVT::v8f32,  28 }, // SNB from http://www.agner.org/
2564     { ISD::FSQRT,      MVT::f64,    21 }, // SNB from http://www.agner.org/
2565     { ISD::FSQRT,      MVT::v2f64,  21 }, // SNB from http://www.agner.org/
2566     { ISD::FSQRT,      MVT::v4f64,  43 }, // SNB from http://www.agner.org/
2567   };
2568   static const CostTblEntry GLMCostTbl[] = {
2569     { ISD::FSQRT, MVT::f32,   19 }, // sqrtss
2570     { ISD::FSQRT, MVT::v4f32, 37 }, // sqrtps
2571     { ISD::FSQRT, MVT::f64,   34 }, // sqrtsd
2572     { ISD::FSQRT, MVT::v2f64, 67 }, // sqrtpd
2573   };
2574   static const CostTblEntry SLMCostTbl[] = {
2575     { ISD::FSQRT, MVT::f32,   20 }, // sqrtss
2576     { ISD::FSQRT, MVT::v4f32, 40 }, // sqrtps
2577     { ISD::FSQRT, MVT::f64,   35 }, // sqrtsd
2578     { ISD::FSQRT, MVT::v2f64, 70 }, // sqrtpd
2579   };
2580   static const CostTblEntry SSE42CostTbl[] = {
2581     { ISD::USUBSAT,    MVT::v4i32,   2 }, // pmaxud + psubd
2582     { ISD::UADDSAT,    MVT::v4i32,   3 }, // not + pminud + paddd
2583     { ISD::FSQRT,      MVT::f32,    18 }, // Nehalem from http://www.agner.org/
2584     { ISD::FSQRT,      MVT::v4f32,  18 }, // Nehalem from http://www.agner.org/
2585   };
2586   static const CostTblEntry SSE41CostTbl[] = {
2587     { ISD::ABS,        MVT::v2i64,   2 }, // BLENDVPD(X,PSUBQ(0,X),X)
2588     { ISD::SMAX,       MVT::v4i32,   1 },
2589     { ISD::SMAX,       MVT::v16i8,   1 },
2590     { ISD::SMIN,       MVT::v4i32,   1 },
2591     { ISD::SMIN,       MVT::v16i8,   1 },
2592     { ISD::UMAX,       MVT::v4i32,   1 },
2593     { ISD::UMAX,       MVT::v8i16,   1 },
2594     { ISD::UMIN,       MVT::v4i32,   1 },
2595     { ISD::UMIN,       MVT::v8i16,   1 },
2596   };
2597   static const CostTblEntry SSSE3CostTbl[] = {
2598     { ISD::ABS,        MVT::v4i32,   1 },
2599     { ISD::ABS,        MVT::v8i16,   1 },
2600     { ISD::ABS,        MVT::v16i8,   1 },
2601     { ISD::BITREVERSE, MVT::v2i64,   5 },
2602     { ISD::BITREVERSE, MVT::v4i32,   5 },
2603     { ISD::BITREVERSE, MVT::v8i16,   5 },
2604     { ISD::BITREVERSE, MVT::v16i8,   5 },
2605     { ISD::BSWAP,      MVT::v2i64,   1 },
2606     { ISD::BSWAP,      MVT::v4i32,   1 },
2607     { ISD::BSWAP,      MVT::v8i16,   1 },
2608     { ISD::CTLZ,       MVT::v2i64,  23 },
2609     { ISD::CTLZ,       MVT::v4i32,  18 },
2610     { ISD::CTLZ,       MVT::v8i16,  14 },
2611     { ISD::CTLZ,       MVT::v16i8,   9 },
2612     { ISD::CTPOP,      MVT::v2i64,   7 },
2613     { ISD::CTPOP,      MVT::v4i32,  11 },
2614     { ISD::CTPOP,      MVT::v8i16,   9 },
2615     { ISD::CTPOP,      MVT::v16i8,   6 },
2616     { ISD::CTTZ,       MVT::v2i64,  10 },
2617     { ISD::CTTZ,       MVT::v4i32,  14 },
2618     { ISD::CTTZ,       MVT::v8i16,  12 },
2619     { ISD::CTTZ,       MVT::v16i8,   9 }
2620   };
2621   static const CostTblEntry SSE2CostTbl[] = {
2622     { ISD::ABS,        MVT::v2i64,   4 },
2623     { ISD::ABS,        MVT::v4i32,   3 },
2624     { ISD::ABS,        MVT::v8i16,   2 },
2625     { ISD::ABS,        MVT::v16i8,   2 },
2626     { ISD::BITREVERSE, MVT::v2i64,  29 },
2627     { ISD::BITREVERSE, MVT::v4i32,  27 },
2628     { ISD::BITREVERSE, MVT::v8i16,  27 },
2629     { ISD::BITREVERSE, MVT::v16i8,  20 },
2630     { ISD::BSWAP,      MVT::v2i64,   7 },
2631     { ISD::BSWAP,      MVT::v4i32,   7 },
2632     { ISD::BSWAP,      MVT::v8i16,   7 },
2633     { ISD::CTLZ,       MVT::v2i64,  25 },
2634     { ISD::CTLZ,       MVT::v4i32,  26 },
2635     { ISD::CTLZ,       MVT::v8i16,  20 },
2636     { ISD::CTLZ,       MVT::v16i8,  17 },
2637     { ISD::CTPOP,      MVT::v2i64,  12 },
2638     { ISD::CTPOP,      MVT::v4i32,  15 },
2639     { ISD::CTPOP,      MVT::v8i16,  13 },
2640     { ISD::CTPOP,      MVT::v16i8,  10 },
2641     { ISD::CTTZ,       MVT::v2i64,  14 },
2642     { ISD::CTTZ,       MVT::v4i32,  18 },
2643     { ISD::CTTZ,       MVT::v8i16,  16 },
2644     { ISD::CTTZ,       MVT::v16i8,  13 },
2645     { ISD::SADDSAT,    MVT::v8i16,   1 },
2646     { ISD::SADDSAT,    MVT::v16i8,   1 },
2647     { ISD::SMAX,       MVT::v8i16,   1 },
2648     { ISD::SMIN,       MVT::v8i16,   1 },
2649     { ISD::SSUBSAT,    MVT::v8i16,   1 },
2650     { ISD::SSUBSAT,    MVT::v16i8,   1 },
2651     { ISD::UADDSAT,    MVT::v8i16,   1 },
2652     { ISD::UADDSAT,    MVT::v16i8,   1 },
2653     { ISD::UMAX,       MVT::v8i16,   2 },
2654     { ISD::UMAX,       MVT::v16i8,   1 },
2655     { ISD::UMIN,       MVT::v8i16,   2 },
2656     { ISD::UMIN,       MVT::v16i8,   1 },
2657     { ISD::USUBSAT,    MVT::v8i16,   1 },
2658     { ISD::USUBSAT,    MVT::v16i8,   1 },
2659     { ISD::FMAXNUM,    MVT::f64,     4 },
2660     { ISD::FMAXNUM,    MVT::v2f64,   4 },
2661     { ISD::FSQRT,      MVT::f64,    32 }, // Nehalem from http://www.agner.org/
2662     { ISD::FSQRT,      MVT::v2f64,  32 }, // Nehalem from http://www.agner.org/
2663   };
2664   static const CostTblEntry SSE1CostTbl[] = {
2665     { ISD::FMAXNUM,    MVT::f32,     4 },
2666     { ISD::FMAXNUM,    MVT::v4f32,   4 },
2667     { ISD::FSQRT,      MVT::f32,    28 }, // Pentium III from http://www.agner.org/
2668     { ISD::FSQRT,      MVT::v4f32,  56 }, // Pentium III from http://www.agner.org/
2669   };
2670   static const CostTblEntry BMI64CostTbl[] = { // 64-bit targets
2671     { ISD::CTTZ,       MVT::i64,     1 },
2672   };
2673   static const CostTblEntry BMI32CostTbl[] = { // 32 or 64-bit targets
2674     { ISD::CTTZ,       MVT::i32,     1 },
2675     { ISD::CTTZ,       MVT::i16,     1 },
2676     { ISD::CTTZ,       MVT::i8,      1 },
2677   };
2678   static const CostTblEntry LZCNT64CostTbl[] = { // 64-bit targets
2679     { ISD::CTLZ,       MVT::i64,     1 },
2680   };
2681   static const CostTblEntry LZCNT32CostTbl[] = { // 32 or 64-bit targets
2682     { ISD::CTLZ,       MVT::i32,     1 },
2683     { ISD::CTLZ,       MVT::i16,     1 },
2684     { ISD::CTLZ,       MVT::i8,      1 },
2685   };
2686   static const CostTblEntry POPCNT64CostTbl[] = { // 64-bit targets
2687     { ISD::CTPOP,      MVT::i64,     1 },
2688   };
2689   static const CostTblEntry POPCNT32CostTbl[] = { // 32 or 64-bit targets
2690     { ISD::CTPOP,      MVT::i32,     1 },
2691     { ISD::CTPOP,      MVT::i16,     1 },
2692     { ISD::CTPOP,      MVT::i8,      1 },
2693   };
2694   static const CostTblEntry X64CostTbl[] = { // 64-bit targets
2695     { ISD::ABS,        MVT::i64,     2 }, // SUB+CMOV
2696     { ISD::BITREVERSE, MVT::i64,    14 },
2697     { ISD::BSWAP,      MVT::i64,     1 },
2698     { ISD::CTLZ,       MVT::i64,     4 }, // BSR+XOR or BSR+XOR+CMOV
2699     { ISD::CTTZ,       MVT::i64,     3 }, // TEST+BSF+CMOV/BRANCH
2700     { ISD::CTPOP,      MVT::i64,    10 },
2701     { ISD::SADDO,      MVT::i64,     1 },
2702     { ISD::UADDO,      MVT::i64,     1 },
2703     { ISD::UMULO,      MVT::i64,     2 }, // mulq + seto
2704   };
2705   static const CostTblEntry X86CostTbl[] = { // 32 or 64-bit targets
2706     { ISD::ABS,        MVT::i32,     2 }, // SUB+CMOV
2707     { ISD::ABS,        MVT::i16,     2 }, // SUB+CMOV
2708     { ISD::BITREVERSE, MVT::i32,    14 },
2709     { ISD::BITREVERSE, MVT::i16,    14 },
2710     { ISD::BITREVERSE, MVT::i8,     11 },
2711     { ISD::BSWAP,      MVT::i32,     1 },
2712     { ISD::BSWAP,      MVT::i16,     1 }, // ROL
2713     { ISD::CTLZ,       MVT::i32,     4 }, // BSR+XOR or BSR+XOR+CMOV
2714     { ISD::CTLZ,       MVT::i16,     4 }, // BSR+XOR or BSR+XOR+CMOV
2715     { ISD::CTLZ,       MVT::i8,      4 }, // BSR+XOR or BSR+XOR+CMOV
2716     { ISD::CTTZ,       MVT::i32,     3 }, // TEST+BSF+CMOV/BRANCH
2717     { ISD::CTTZ,       MVT::i16,     3 }, // TEST+BSF+CMOV/BRANCH
2718     { ISD::CTTZ,       MVT::i8,      3 }, // TEST+BSF+CMOV/BRANCH
2719     { ISD::CTPOP,      MVT::i32,     8 },
2720     { ISD::CTPOP,      MVT::i16,     9 },
2721     { ISD::CTPOP,      MVT::i8,      7 },
2722     { ISD::SADDO,      MVT::i32,     1 },
2723     { ISD::SADDO,      MVT::i16,     1 },
2724     { ISD::SADDO,      MVT::i8,      1 },
2725     { ISD::UADDO,      MVT::i32,     1 },
2726     { ISD::UADDO,      MVT::i16,     1 },
2727     { ISD::UADDO,      MVT::i8,      1 },
2728     { ISD::UMULO,      MVT::i32,     2 }, // mul + seto
2729     { ISD::UMULO,      MVT::i16,     2 },
2730     { ISD::UMULO,      MVT::i8,      2 },
2731   };
2732 
2733   Type *RetTy = ICA.getReturnType();
2734   Type *OpTy = RetTy;
2735   Intrinsic::ID IID = ICA.getID();
2736   unsigned ISD = ISD::DELETED_NODE;
2737   switch (IID) {
2738   default:
2739     break;
2740   case Intrinsic::abs:
2741     ISD = ISD::ABS;
2742     break;
2743   case Intrinsic::bitreverse:
2744     ISD = ISD::BITREVERSE;
2745     break;
2746   case Intrinsic::bswap:
2747     ISD = ISD::BSWAP;
2748     break;
2749   case Intrinsic::ctlz:
2750     ISD = ISD::CTLZ;
2751     break;
2752   case Intrinsic::ctpop:
2753     ISD = ISD::CTPOP;
2754     break;
2755   case Intrinsic::cttz:
2756     ISD = ISD::CTTZ;
2757     break;
2758   case Intrinsic::maxnum:
2759   case Intrinsic::minnum:
2760     // FMINNUM has same costs so don't duplicate.
2761     ISD = ISD::FMAXNUM;
2762     break;
2763   case Intrinsic::sadd_sat:
2764     ISD = ISD::SADDSAT;
2765     break;
2766   case Intrinsic::smax:
2767     ISD = ISD::SMAX;
2768     break;
2769   case Intrinsic::smin:
2770     ISD = ISD::SMIN;
2771     break;
2772   case Intrinsic::ssub_sat:
2773     ISD = ISD::SSUBSAT;
2774     break;
2775   case Intrinsic::uadd_sat:
2776     ISD = ISD::UADDSAT;
2777     break;
2778   case Intrinsic::umax:
2779     ISD = ISD::UMAX;
2780     break;
2781   case Intrinsic::umin:
2782     ISD = ISD::UMIN;
2783     break;
2784   case Intrinsic::usub_sat:
2785     ISD = ISD::USUBSAT;
2786     break;
2787   case Intrinsic::sqrt:
2788     ISD = ISD::FSQRT;
2789     break;
2790   case Intrinsic::sadd_with_overflow:
2791   case Intrinsic::ssub_with_overflow:
2792     // SSUBO has same costs so don't duplicate.
2793     ISD = ISD::SADDO;
2794     OpTy = RetTy->getContainedType(0);
2795     break;
2796   case Intrinsic::uadd_with_overflow:
2797   case Intrinsic::usub_with_overflow:
2798     // USUBO has same costs so don't duplicate.
2799     ISD = ISD::UADDO;
2800     OpTy = RetTy->getContainedType(0);
2801     break;
2802   case Intrinsic::umul_with_overflow:
2803   case Intrinsic::smul_with_overflow:
2804     // SMULO has same costs so don't duplicate.
2805     ISD = ISD::UMULO;
2806     OpTy = RetTy->getContainedType(0);
2807     break;
2808   }
2809 
2810   if (ISD != ISD::DELETED_NODE) {
2811     // Legalize the type.
2812     std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, OpTy);
2813     MVT MTy = LT.second;
2814 
2815     // Attempt to lookup cost.
2816     if (ISD == ISD::BITREVERSE && ST->hasGFNI() && ST->hasSSSE3() &&
2817         MTy.isVector()) {
2818       // With PSHUFB the code is very similar for all types. If we have integer
2819       // byte operations, we just need a GF2P8AFFINEQB for vXi8. For other types
2820       // we also need a PSHUFB.
2821       unsigned Cost = MTy.getVectorElementType() == MVT::i8 ? 1 : 2;
2822 
2823       // Without byte operations, we need twice as many GF2P8AFFINEQB and PSHUFB
2824       // instructions. We also need an extract and an insert.
2825       if (!(MTy.is128BitVector() || (ST->hasAVX2() && MTy.is256BitVector()) ||
2826             (ST->hasBWI() && MTy.is512BitVector())))
2827         Cost = Cost * 2 + 2;
2828 
2829       return LT.first * Cost;
2830     }
2831 
2832     auto adjustTableCost = [](const CostTblEntry &Entry,
2833                               InstructionCost LegalizationCost,
2834                               FastMathFlags FMF) {
2835       // If there are no NANs to deal with, then these are reduced to a
2836       // single MIN** or MAX** instruction instead of the MIN/CMP/SELECT that we
2837       // assume is used in the non-fast case.
2838       if (Entry.ISD == ISD::FMAXNUM || Entry.ISD == ISD::FMINNUM) {
2839         if (FMF.noNaNs())
2840           return LegalizationCost * 1;
2841       }
2842       return LegalizationCost * (int)Entry.Cost;
2843     };
2844 
2845     if (ST->useGLMDivSqrtCosts())
2846       if (const auto *Entry = CostTableLookup(GLMCostTbl, ISD, MTy))
2847         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
2848 
2849     if (ST->isSLM())
2850       if (const auto *Entry = CostTableLookup(SLMCostTbl, ISD, MTy))
2851         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
2852 
2853     if (ST->hasCDI())
2854       if (const auto *Entry = CostTableLookup(AVX512CDCostTbl, ISD, MTy))
2855         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
2856 
2857     if (ST->hasBWI())
2858       if (const auto *Entry = CostTableLookup(AVX512BWCostTbl, ISD, MTy))
2859         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
2860 
2861     if (ST->hasAVX512())
2862       if (const auto *Entry = CostTableLookup(AVX512CostTbl, ISD, MTy))
2863         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
2864 
2865     if (ST->hasXOP())
2866       if (const auto *Entry = CostTableLookup(XOPCostTbl, ISD, MTy))
2867         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
2868 
2869     if (ST->hasAVX2())
2870       if (const auto *Entry = CostTableLookup(AVX2CostTbl, ISD, MTy))
2871         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
2872 
2873     if (ST->hasAVX())
2874       if (const auto *Entry = CostTableLookup(AVX1CostTbl, ISD, MTy))
2875         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
2876 
2877     if (ST->hasSSE42())
2878       if (const auto *Entry = CostTableLookup(SSE42CostTbl, ISD, MTy))
2879         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
2880 
2881     if (ST->hasSSE41())
2882       if (const auto *Entry = CostTableLookup(SSE41CostTbl, ISD, MTy))
2883         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
2884 
2885     if (ST->hasSSSE3())
2886       if (const auto *Entry = CostTableLookup(SSSE3CostTbl, ISD, MTy))
2887         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
2888 
2889     if (ST->hasSSE2())
2890       if (const auto *Entry = CostTableLookup(SSE2CostTbl, ISD, MTy))
2891         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
2892 
2893     if (ST->hasSSE1())
2894       if (const auto *Entry = CostTableLookup(SSE1CostTbl, ISD, MTy))
2895         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
2896 
2897     if (ST->hasBMI()) {
2898       if (ST->is64Bit())
2899         if (const auto *Entry = CostTableLookup(BMI64CostTbl, ISD, MTy))
2900           return adjustTableCost(*Entry, LT.first, ICA.getFlags());
2901 
2902       if (const auto *Entry = CostTableLookup(BMI32CostTbl, ISD, MTy))
2903         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
2904     }
2905 
2906     if (ST->hasLZCNT()) {
2907       if (ST->is64Bit())
2908         if (const auto *Entry = CostTableLookup(LZCNT64CostTbl, ISD, MTy))
2909           return adjustTableCost(*Entry, LT.first, ICA.getFlags());
2910 
2911       if (const auto *Entry = CostTableLookup(LZCNT32CostTbl, ISD, MTy))
2912         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
2913     }
2914 
2915     if (ST->hasPOPCNT()) {
2916       if (ST->is64Bit())
2917         if (const auto *Entry = CostTableLookup(POPCNT64CostTbl, ISD, MTy))
2918           return adjustTableCost(*Entry, LT.first, ICA.getFlags());
2919 
2920       if (const auto *Entry = CostTableLookup(POPCNT32CostTbl, ISD, MTy))
2921         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
2922     }
2923 
2924     if (ISD == ISD::BSWAP && ST->hasMOVBE() && ST->hasFastMOVBE()) {
2925       if (const Instruction *II = ICA.getInst()) {
2926         if (II->hasOneUse() && isa<StoreInst>(II->user_back()))
2927           return TTI::TCC_Free;
2928         if (auto *LI = dyn_cast<LoadInst>(II->getOperand(0))) {
2929           if (LI->hasOneUse())
2930             return TTI::TCC_Free;
2931         }
2932       }
2933     }
2934 
2935     // TODO - add BMI (TZCNT) scalar handling
2936 
2937     if (ST->is64Bit())
2938       if (const auto *Entry = CostTableLookup(X64CostTbl, ISD, MTy))
2939         return adjustTableCost(*Entry, LT.first, ICA.getFlags());
2940 
2941     if (const auto *Entry = CostTableLookup(X86CostTbl, ISD, MTy))
2942       return adjustTableCost(*Entry, LT.first, ICA.getFlags());
2943   }
2944 
2945   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
2946 }
2947 
2948 InstructionCost
2949 X86TTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
2950                                   TTI::TargetCostKind CostKind) {
2951   if (ICA.isTypeBasedOnly())
2952     return getTypeBasedIntrinsicInstrCost(ICA, CostKind);
2953 
2954   static const CostTblEntry AVX512CostTbl[] = {
2955     { ISD::ROTL,       MVT::v8i64,   1 },
2956     { ISD::ROTL,       MVT::v4i64,   1 },
2957     { ISD::ROTL,       MVT::v2i64,   1 },
2958     { ISD::ROTL,       MVT::v16i32,  1 },
2959     { ISD::ROTL,       MVT::v8i32,   1 },
2960     { ISD::ROTL,       MVT::v4i32,   1 },
2961     { ISD::ROTR,       MVT::v8i64,   1 },
2962     { ISD::ROTR,       MVT::v4i64,   1 },
2963     { ISD::ROTR,       MVT::v2i64,   1 },
2964     { ISD::ROTR,       MVT::v16i32,  1 },
2965     { ISD::ROTR,       MVT::v8i32,   1 },
2966     { ISD::ROTR,       MVT::v4i32,   1 }
2967   };
2968   // XOP: ROTL = VPROT(X,Y), ROTR = VPROT(X,SUB(0,Y))
2969   static const CostTblEntry XOPCostTbl[] = {
2970     { ISD::ROTL,       MVT::v4i64,   4 },
2971     { ISD::ROTL,       MVT::v8i32,   4 },
2972     { ISD::ROTL,       MVT::v16i16,  4 },
2973     { ISD::ROTL,       MVT::v32i8,   4 },
2974     { ISD::ROTL,       MVT::v2i64,   1 },
2975     { ISD::ROTL,       MVT::v4i32,   1 },
2976     { ISD::ROTL,       MVT::v8i16,   1 },
2977     { ISD::ROTL,       MVT::v16i8,   1 },
2978     { ISD::ROTR,       MVT::v4i64,   6 },
2979     { ISD::ROTR,       MVT::v8i32,   6 },
2980     { ISD::ROTR,       MVT::v16i16,  6 },
2981     { ISD::ROTR,       MVT::v32i8,   6 },
2982     { ISD::ROTR,       MVT::v2i64,   2 },
2983     { ISD::ROTR,       MVT::v4i32,   2 },
2984     { ISD::ROTR,       MVT::v8i16,   2 },
2985     { ISD::ROTR,       MVT::v16i8,   2 }
2986   };
2987   static const CostTblEntry X64CostTbl[] = { // 64-bit targets
2988     { ISD::ROTL,       MVT::i64,     1 },
2989     { ISD::ROTR,       MVT::i64,     1 },
2990     { ISD::FSHL,       MVT::i64,     4 }
2991   };
2992   static const CostTblEntry X86CostTbl[] = { // 32 or 64-bit targets
2993     { ISD::ROTL,       MVT::i32,     1 },
2994     { ISD::ROTL,       MVT::i16,     1 },
2995     { ISD::ROTL,       MVT::i8,      1 },
2996     { ISD::ROTR,       MVT::i32,     1 },
2997     { ISD::ROTR,       MVT::i16,     1 },
2998     { ISD::ROTR,       MVT::i8,      1 },
2999     { ISD::FSHL,       MVT::i32,     4 },
3000     { ISD::FSHL,       MVT::i16,     4 },
3001     { ISD::FSHL,       MVT::i8,      4 }
3002   };
3003 
3004   Intrinsic::ID IID = ICA.getID();
3005   Type *RetTy = ICA.getReturnType();
3006   const SmallVectorImpl<const Value *> &Args = ICA.getArgs();
3007   unsigned ISD = ISD::DELETED_NODE;
3008   switch (IID) {
3009   default:
3010     break;
3011   case Intrinsic::fshl:
3012     ISD = ISD::FSHL;
3013     if (Args[0] == Args[1])
3014       ISD = ISD::ROTL;
3015     break;
3016   case Intrinsic::fshr:
3017     // FSHR has same costs so don't duplicate.
3018     ISD = ISD::FSHL;
3019     if (Args[0] == Args[1])
3020       ISD = ISD::ROTR;
3021     break;
3022   }
3023 
3024   if (ISD != ISD::DELETED_NODE) {
3025     // Legalize the type.
3026     std::pair<InstructionCost, MVT> LT =
3027         TLI->getTypeLegalizationCost(DL, RetTy);
3028     MVT MTy = LT.second;
3029 
3030     // Attempt to lookup cost.
3031     if (ST->hasAVX512())
3032       if (const auto *Entry = CostTableLookup(AVX512CostTbl, ISD, MTy))
3033         return LT.first * Entry->Cost;
3034 
3035     if (ST->hasXOP())
3036       if (const auto *Entry = CostTableLookup(XOPCostTbl, ISD, MTy))
3037         return LT.first * Entry->Cost;
3038 
3039     if (ST->is64Bit())
3040       if (const auto *Entry = CostTableLookup(X64CostTbl, ISD, MTy))
3041         return LT.first * Entry->Cost;
3042 
3043     if (const auto *Entry = CostTableLookup(X86CostTbl, ISD, MTy))
3044       return LT.first * Entry->Cost;
3045   }
3046 
3047   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
3048 }
3049 
3050 InstructionCost X86TTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val,
3051                                                unsigned Index) {
3052   static const CostTblEntry SLMCostTbl[] = {
3053      { ISD::EXTRACT_VECTOR_ELT,       MVT::i8,      4 },
3054      { ISD::EXTRACT_VECTOR_ELT,       MVT::i16,     4 },
3055      { ISD::EXTRACT_VECTOR_ELT,       MVT::i32,     4 },
3056      { ISD::EXTRACT_VECTOR_ELT,       MVT::i64,     7 }
3057    };
3058 
3059   assert(Val->isVectorTy() && "This must be a vector type");
3060   Type *ScalarType = Val->getScalarType();
3061   int RegisterFileMoveCost = 0;
3062 
3063   if (Index != -1U && (Opcode == Instruction::ExtractElement ||
3064                        Opcode == Instruction::InsertElement)) {
3065     // Legalize the type.
3066     std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Val);
3067 
3068     // This type is legalized to a scalar type.
3069     if (!LT.second.isVector())
3070       return 0;
3071 
3072     // The type may be split. Normalize the index to the new type.
3073     unsigned NumElts = LT.second.getVectorNumElements();
3074     unsigned SubNumElts = NumElts;
3075     Index = Index % NumElts;
3076 
3077     // For >128-bit vectors, we need to extract higher 128-bit subvectors.
3078     // For inserts, we also need to insert the subvector back.
3079     if (LT.second.getSizeInBits() > 128) {
3080       assert((LT.second.getSizeInBits() % 128) == 0 && "Illegal vector");
3081       unsigned NumSubVecs = LT.second.getSizeInBits() / 128;
3082       SubNumElts = NumElts / NumSubVecs;
3083       if (SubNumElts <= Index) {
3084         RegisterFileMoveCost += (Opcode == Instruction::InsertElement ? 2 : 1);
3085         Index %= SubNumElts;
3086       }
3087     }
3088 
3089     if (Index == 0) {
3090       // Floating point scalars are already located in index #0.
3091       // Many insertions to #0 can fold away for scalar fp-ops, so let's assume
3092       // true for all.
3093       if (ScalarType->isFloatingPointTy())
3094         return RegisterFileMoveCost;
3095 
3096       // Assume movd/movq XMM -> GPR is relatively cheap on all targets.
3097       if (ScalarType->isIntegerTy() && Opcode == Instruction::ExtractElement)
3098         return 1 + RegisterFileMoveCost;
3099     }
3100 
3101     int ISD = TLI->InstructionOpcodeToISD(Opcode);
3102     assert(ISD && "Unexpected vector opcode");
3103     MVT MScalarTy = LT.second.getScalarType();
3104     if (ST->isSLM())
3105       if (auto *Entry = CostTableLookup(SLMCostTbl, ISD, MScalarTy))
3106         return Entry->Cost + RegisterFileMoveCost;
3107 
3108     // Assume pinsr/pextr XMM <-> GPR is relatively cheap on all targets.
3109     if ((MScalarTy == MVT::i16 && ST->hasSSE2()) ||
3110         (MScalarTy.isInteger() && ST->hasSSE41()))
3111       return 1 + RegisterFileMoveCost;
3112 
3113     // Assume insertps is relatively cheap on all targets.
3114     if (MScalarTy == MVT::f32 && ST->hasSSE41() &&
3115         Opcode == Instruction::InsertElement)
3116       return 1 + RegisterFileMoveCost;
3117 
3118     // For extractions we just need to shuffle the element to index 0, which
3119     // should be very cheap (assume cost = 1). For insertions we need to shuffle
3120     // the elements to its destination. In both cases we must handle the
3121     // subvector move(s).
3122     // If the vector type is already less than 128-bits then don't reduce it.
3123     // TODO: Under what circumstances should we shuffle using the full width?
3124     InstructionCost ShuffleCost = 1;
3125     if (Opcode == Instruction::InsertElement) {
3126       auto *SubTy = cast<VectorType>(Val);
3127       EVT VT = TLI->getValueType(DL, Val);
3128       if (VT.getScalarType() != MScalarTy || VT.getSizeInBits() >= 128)
3129         SubTy = FixedVectorType::get(ScalarType, SubNumElts);
3130       ShuffleCost =
3131           getShuffleCost(TTI::SK_PermuteTwoSrc, SubTy, None, 0, SubTy);
3132     }
3133     int IntOrFpCost = ScalarType->isFloatingPointTy() ? 0 : 1;
3134     return ShuffleCost + IntOrFpCost + RegisterFileMoveCost;
3135   }
3136 
3137   // Add to the base cost if we know that the extracted element of a vector is
3138   // destined to be moved to and used in the integer register file.
3139   if (Opcode == Instruction::ExtractElement && ScalarType->isPointerTy())
3140     RegisterFileMoveCost += 1;
3141 
3142   return BaseT::getVectorInstrCost(Opcode, Val, Index) + RegisterFileMoveCost;
3143 }
3144 
3145 InstructionCost X86TTIImpl::getScalarizationOverhead(VectorType *Ty,
3146                                                      const APInt &DemandedElts,
3147                                                      bool Insert,
3148                                                      bool Extract) {
3149   InstructionCost Cost = 0;
3150 
3151   // For insertions, a ISD::BUILD_VECTOR style vector initialization can be much
3152   // cheaper than an accumulation of ISD::INSERT_VECTOR_ELT.
3153   if (Insert) {
3154     std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
3155     MVT MScalarTy = LT.second.getScalarType();
3156 
3157     if ((MScalarTy == MVT::i16 && ST->hasSSE2()) ||
3158         (MScalarTy.isInteger() && ST->hasSSE41()) ||
3159         (MScalarTy == MVT::f32 && ST->hasSSE41())) {
3160       // For types we can insert directly, insertion into 128-bit sub vectors is
3161       // cheap, followed by a cheap chain of concatenations.
3162       if (LT.second.getSizeInBits() <= 128) {
3163         Cost +=
3164             BaseT::getScalarizationOverhead(Ty, DemandedElts, Insert, false);
3165       } else {
3166         // In each 128-lane, if at least one index is demanded but not all
3167         // indices are demanded and this 128-lane is not the first 128-lane of
3168         // the legalized-vector, then this 128-lane needs a extracti128; If in
3169         // each 128-lane, there is at least one demanded index, this 128-lane
3170         // needs a inserti128.
3171 
3172         // The following cases will help you build a better understanding:
3173         // Assume we insert several elements into a v8i32 vector in avx2,
3174         // Case#1: inserting into 1th index needs vpinsrd + inserti128.
3175         // Case#2: inserting into 5th index needs extracti128 + vpinsrd +
3176         // inserti128.
3177         // Case#3: inserting into 4,5,6,7 index needs 4*vpinsrd + inserti128.
3178         const int CostValue = *LT.first.getValue();
3179         assert(CostValue >= 0 && "Negative cost!");
3180         unsigned Num128Lanes = LT.second.getSizeInBits() / 128 * CostValue;
3181         unsigned NumElts = LT.second.getVectorNumElements() * CostValue;
3182         APInt WidenedDemandedElts = DemandedElts.zextOrSelf(NumElts);
3183         unsigned Scale = NumElts / Num128Lanes;
3184         // We iterate each 128-lane, and check if we need a
3185         // extracti128/inserti128 for this 128-lane.
3186         for (unsigned I = 0; I < NumElts; I += Scale) {
3187           APInt Mask = WidenedDemandedElts.getBitsSet(NumElts, I, I + Scale);
3188           APInt MaskedDE = Mask & WidenedDemandedElts;
3189           unsigned Population = MaskedDE.countPopulation();
3190           Cost += (Population > 0 && Population != Scale &&
3191                    I % LT.second.getVectorNumElements() != 0);
3192           Cost += Population > 0;
3193         }
3194         Cost += DemandedElts.countPopulation();
3195 
3196         // For vXf32 cases, insertion into the 0'th index in each v4f32
3197         // 128-bit vector is free.
3198         // NOTE: This assumes legalization widens vXf32 vectors.
3199         if (MScalarTy == MVT::f32)
3200           for (unsigned i = 0, e = cast<FixedVectorType>(Ty)->getNumElements();
3201                i < e; i += 4)
3202             if (DemandedElts[i])
3203               Cost--;
3204       }
3205     } else if (LT.second.isVector()) {
3206       // Without fast insertion, we need to use MOVD/MOVQ to pass each demanded
3207       // integer element as a SCALAR_TO_VECTOR, then we build the vector as a
3208       // series of UNPCK followed by CONCAT_VECTORS - all of these can be
3209       // considered cheap.
3210       if (Ty->isIntOrIntVectorTy())
3211         Cost += DemandedElts.countPopulation();
3212 
3213       // Get the smaller of the legalized or original pow2-extended number of
3214       // vector elements, which represents the number of unpacks we'll end up
3215       // performing.
3216       unsigned NumElts = LT.second.getVectorNumElements();
3217       unsigned Pow2Elts =
3218           PowerOf2Ceil(cast<FixedVectorType>(Ty)->getNumElements());
3219       Cost += (std::min<unsigned>(NumElts, Pow2Elts) - 1) * LT.first;
3220     }
3221   }
3222 
3223   // TODO: Use default extraction for now, but we should investigate extending this
3224   // to handle repeated subvector extraction.
3225   if (Extract)
3226     Cost += BaseT::getScalarizationOverhead(Ty, DemandedElts, false, Extract);
3227 
3228   return Cost;
3229 }
3230 
3231 InstructionCost X86TTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
3232                                             MaybeAlign Alignment,
3233                                             unsigned AddressSpace,
3234                                             TTI::TargetCostKind CostKind,
3235                                             const Instruction *I) {
3236   // TODO: Handle other cost kinds.
3237   if (CostKind != TTI::TCK_RecipThroughput) {
3238     if (auto *SI = dyn_cast_or_null<StoreInst>(I)) {
3239       // Store instruction with index and scale costs 2 Uops.
3240       // Check the preceding GEP to identify non-const indices.
3241       if (auto *GEP = dyn_cast<GetElementPtrInst>(SI->getPointerOperand())) {
3242         if (!all_of(GEP->indices(), [](Value *V) { return isa<Constant>(V); }))
3243           return TTI::TCC_Basic * 2;
3244       }
3245     }
3246     return TTI::TCC_Basic;
3247   }
3248 
3249   assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
3250          "Invalid Opcode");
3251   // Type legalization can't handle structs
3252   if (TLI->getValueType(DL, Src, true) == MVT::Other)
3253     return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
3254                                   CostKind);
3255 
3256   // Handle non-power-of-two vectors such as <3 x float> and <48 x i16>
3257   if (auto *VTy = dyn_cast<FixedVectorType>(Src)) {
3258     const unsigned NumElem = VTy->getNumElements();
3259     if (!isPowerOf2_32(NumElem)) {
3260       // Factorize NumElem into sum of power-of-two.
3261       InstructionCost Cost = 0;
3262       unsigned NumElemDone = 0;
3263       for (unsigned NumElemLeft = NumElem, Factor;
3264            Factor = PowerOf2Floor(NumElemLeft), NumElemLeft > 0;
3265            NumElemLeft -= Factor) {
3266         Type *SubTy = FixedVectorType::get(VTy->getScalarType(), Factor);
3267         unsigned SubTyBytes = SubTy->getPrimitiveSizeInBits() / 8;
3268 
3269         Cost +=
3270             getMemoryOpCost(Opcode, SubTy, Alignment, AddressSpace, CostKind);
3271 
3272         std::pair<InstructionCost, MVT> LST =
3273             TLI->getTypeLegalizationCost(DL, SubTy);
3274         if (!LST.second.isVector()) {
3275           APInt DemandedElts =
3276               APInt::getBitsSet(NumElem, NumElemDone, NumElemDone + Factor);
3277           Cost += getScalarizationOverhead(VTy, DemandedElts,
3278                                            Opcode == Instruction::Load,
3279                                            Opcode == Instruction::Store);
3280         }
3281 
3282         NumElemDone += Factor;
3283         Alignment = commonAlignment(Alignment.valueOrOne(), SubTyBytes);
3284       }
3285       assert(NumElemDone == NumElem && "Processed wrong element count?");
3286       return Cost;
3287     }
3288   }
3289 
3290   // Legalize the type.
3291   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
3292 
3293   // Each load/store unit costs 1.
3294   InstructionCost Cost = LT.first * 1;
3295 
3296   // This isn't exactly right. We're using slow unaligned 32-byte accesses as a
3297   // proxy for a double-pumped AVX memory interface such as on Sandybridge.
3298   if (LT.second.getStoreSize() == 32 && ST->isUnalignedMem32Slow())
3299     Cost *= 2;
3300 
3301   return Cost;
3302 }
3303 
3304 InstructionCost
3305 X86TTIImpl::getMaskedMemoryOpCost(unsigned Opcode, Type *SrcTy, Align Alignment,
3306                                   unsigned AddressSpace,
3307                                   TTI::TargetCostKind CostKind) {
3308   bool IsLoad = (Instruction::Load == Opcode);
3309   bool IsStore = (Instruction::Store == Opcode);
3310 
3311   auto *SrcVTy = dyn_cast<FixedVectorType>(SrcTy);
3312   if (!SrcVTy)
3313     // To calculate scalar take the regular cost, without mask
3314     return getMemoryOpCost(Opcode, SrcTy, Alignment, AddressSpace, CostKind);
3315 
3316   unsigned NumElem = SrcVTy->getNumElements();
3317   auto *MaskTy =
3318       FixedVectorType::get(Type::getInt8Ty(SrcVTy->getContext()), NumElem);
3319   if ((IsLoad && !isLegalMaskedLoad(SrcVTy, Alignment)) ||
3320       (IsStore && !isLegalMaskedStore(SrcVTy, Alignment)) ||
3321       !isPowerOf2_32(NumElem)) {
3322     // Scalarization
3323     APInt DemandedElts = APInt::getAllOnesValue(NumElem);
3324     InstructionCost MaskSplitCost =
3325         getScalarizationOverhead(MaskTy, DemandedElts, false, true);
3326     InstructionCost ScalarCompareCost = getCmpSelInstrCost(
3327         Instruction::ICmp, Type::getInt8Ty(SrcVTy->getContext()), nullptr,
3328         CmpInst::BAD_ICMP_PREDICATE, CostKind);
3329     InstructionCost BranchCost = getCFInstrCost(Instruction::Br, CostKind);
3330     InstructionCost MaskCmpCost = NumElem * (BranchCost + ScalarCompareCost);
3331     InstructionCost ValueSplitCost =
3332         getScalarizationOverhead(SrcVTy, DemandedElts, IsLoad, IsStore);
3333     InstructionCost MemopCost =
3334         NumElem * BaseT::getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
3335                                          Alignment, AddressSpace, CostKind);
3336     return MemopCost + ValueSplitCost + MaskSplitCost + MaskCmpCost;
3337   }
3338 
3339   // Legalize the type.
3340   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, SrcVTy);
3341   auto VT = TLI->getValueType(DL, SrcVTy);
3342   InstructionCost Cost = 0;
3343   if (VT.isSimple() && LT.second != VT.getSimpleVT() &&
3344       LT.second.getVectorNumElements() == NumElem)
3345     // Promotion requires expand/truncate for data and a shuffle for mask.
3346     Cost += getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVTy, None, 0, nullptr) +
3347             getShuffleCost(TTI::SK_PermuteTwoSrc, MaskTy, None, 0, nullptr);
3348 
3349   else if (LT.second.getVectorNumElements() > NumElem) {
3350     auto *NewMaskTy = FixedVectorType::get(MaskTy->getElementType(),
3351                                            LT.second.getVectorNumElements());
3352     // Expanding requires fill mask with zeroes
3353     Cost += getShuffleCost(TTI::SK_InsertSubvector, NewMaskTy, None, 0, MaskTy);
3354   }
3355 
3356   // Pre-AVX512 - each maskmov load costs 2 + store costs ~8.
3357   if (!ST->hasAVX512())
3358     return Cost + LT.first * (IsLoad ? 2 : 8);
3359 
3360   // AVX-512 masked load/store is cheapper
3361   return Cost + LT.first;
3362 }
3363 
3364 InstructionCost X86TTIImpl::getAddressComputationCost(Type *Ty,
3365                                                       ScalarEvolution *SE,
3366                                                       const SCEV *Ptr) {
3367   // Address computations in vectorized code with non-consecutive addresses will
3368   // likely result in more instructions compared to scalar code where the
3369   // computation can more often be merged into the index mode. The resulting
3370   // extra micro-ops can significantly decrease throughput.
3371   const unsigned NumVectorInstToHideOverhead = 10;
3372 
3373   // Cost modeling of Strided Access Computation is hidden by the indexing
3374   // modes of X86 regardless of the stride value. We dont believe that there
3375   // is a difference between constant strided access in gerenal and constant
3376   // strided value which is less than or equal to 64.
3377   // Even in the case of (loop invariant) stride whose value is not known at
3378   // compile time, the address computation will not incur more than one extra
3379   // ADD instruction.
3380   if (Ty->isVectorTy() && SE) {
3381     if (!BaseT::isStridedAccess(Ptr))
3382       return NumVectorInstToHideOverhead;
3383     if (!BaseT::getConstantStrideStep(SE, Ptr))
3384       return 1;
3385   }
3386 
3387   return BaseT::getAddressComputationCost(Ty, SE, Ptr);
3388 }
3389 
3390 InstructionCost
3391 X86TTIImpl::getArithmeticReductionCost(unsigned Opcode, VectorType *ValTy,
3392                                        bool IsPairwise,
3393                                        TTI::TargetCostKind CostKind) {
3394   // Just use the default implementation for pair reductions.
3395   if (IsPairwise)
3396     return BaseT::getArithmeticReductionCost(Opcode, ValTy, IsPairwise, CostKind);
3397 
3398   // We use the Intel Architecture Code Analyzer(IACA) to measure the throughput
3399   // and make it as the cost.
3400 
3401   static const CostTblEntry SLMCostTblNoPairWise[] = {
3402     { ISD::FADD,  MVT::v2f64,   3 },
3403     { ISD::ADD,   MVT::v2i64,   5 },
3404   };
3405 
3406   static const CostTblEntry SSE2CostTblNoPairWise[] = {
3407     { ISD::FADD,  MVT::v2f64,   2 },
3408     { ISD::FADD,  MVT::v2f32,   2 },
3409     { ISD::FADD,  MVT::v4f32,   4 },
3410     { ISD::ADD,   MVT::v2i64,   2 },      // The data reported by the IACA tool is "1.6".
3411     { ISD::ADD,   MVT::v2i32,   2 }, // FIXME: chosen to be less than v4i32
3412     { ISD::ADD,   MVT::v4i32,   3 },      // The data reported by the IACA tool is "3.3".
3413     { ISD::ADD,   MVT::v2i16,   2 },      // The data reported by the IACA tool is "4.3".
3414     { ISD::ADD,   MVT::v4i16,   3 },      // The data reported by the IACA tool is "4.3".
3415     { ISD::ADD,   MVT::v8i16,   4 },      // The data reported by the IACA tool is "4.3".
3416     { ISD::ADD,   MVT::v2i8,    2 },
3417     { ISD::ADD,   MVT::v4i8,    2 },
3418     { ISD::ADD,   MVT::v8i8,    2 },
3419     { ISD::ADD,   MVT::v16i8,   3 },
3420   };
3421 
3422   static const CostTblEntry AVX1CostTblNoPairWise[] = {
3423     { ISD::FADD,  MVT::v4f64,   3 },
3424     { ISD::FADD,  MVT::v4f32,   3 },
3425     { ISD::FADD,  MVT::v8f32,   4 },
3426     { ISD::ADD,   MVT::v2i64,   1 },      // The data reported by the IACA tool is "1.5".
3427     { ISD::ADD,   MVT::v4i64,   3 },
3428     { ISD::ADD,   MVT::v8i32,   5 },
3429     { ISD::ADD,   MVT::v16i16,  5 },
3430     { ISD::ADD,   MVT::v32i8,   4 },
3431   };
3432 
3433   int ISD = TLI->InstructionOpcodeToISD(Opcode);
3434   assert(ISD && "Invalid opcode");
3435 
3436   // Before legalizing the type, give a chance to look up illegal narrow types
3437   // in the table.
3438   // FIXME: Is there a better way to do this?
3439   EVT VT = TLI->getValueType(DL, ValTy);
3440   if (VT.isSimple()) {
3441     MVT MTy = VT.getSimpleVT();
3442     if (ST->isSLM())
3443       if (const auto *Entry = CostTableLookup(SLMCostTblNoPairWise, ISD, MTy))
3444         return Entry->Cost;
3445 
3446     if (ST->hasAVX())
3447       if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
3448         return Entry->Cost;
3449 
3450     if (ST->hasSSE2())
3451       if (const auto *Entry = CostTableLookup(SSE2CostTblNoPairWise, ISD, MTy))
3452         return Entry->Cost;
3453   }
3454 
3455   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
3456 
3457   MVT MTy = LT.second;
3458 
3459   auto *ValVTy = cast<FixedVectorType>(ValTy);
3460 
3461   // Special case: vXi8 mul reductions are performed as vXi16.
3462   if (ISD == ISD::MUL && MTy.getScalarType() == MVT::i8) {
3463     auto *WideSclTy = IntegerType::get(ValVTy->getContext(), 16);
3464     auto *WideVecTy = FixedVectorType::get(WideSclTy, ValVTy->getNumElements());
3465     return getCastInstrCost(Instruction::ZExt, WideVecTy, ValTy,
3466                             TargetTransformInfo::CastContextHint::None,
3467                             CostKind) +
3468            getArithmeticReductionCost(Opcode, WideVecTy, IsPairwise, CostKind);
3469   }
3470 
3471   InstructionCost ArithmeticCost = 0;
3472   if (LT.first != 1 && MTy.isVector() &&
3473       MTy.getVectorNumElements() < ValVTy->getNumElements()) {
3474     // Type needs to be split. We need LT.first - 1 arithmetic ops.
3475     auto *SingleOpTy = FixedVectorType::get(ValVTy->getElementType(),
3476                                             MTy.getVectorNumElements());
3477     ArithmeticCost = getArithmeticInstrCost(Opcode, SingleOpTy, CostKind);
3478     ArithmeticCost *= LT.first - 1;
3479   }
3480 
3481   if (ST->isSLM())
3482     if (const auto *Entry = CostTableLookup(SLMCostTblNoPairWise, ISD, MTy))
3483       return ArithmeticCost + Entry->Cost;
3484 
3485   if (ST->hasAVX())
3486     if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
3487       return ArithmeticCost + Entry->Cost;
3488 
3489   if (ST->hasSSE2())
3490     if (const auto *Entry = CostTableLookup(SSE2CostTblNoPairWise, ISD, MTy))
3491       return ArithmeticCost + Entry->Cost;
3492 
3493   // FIXME: These assume a naive kshift+binop lowering, which is probably
3494   // conservative in most cases.
3495   static const CostTblEntry AVX512BoolReduction[] = {
3496     { ISD::AND,  MVT::v2i1,   3 },
3497     { ISD::AND,  MVT::v4i1,   5 },
3498     { ISD::AND,  MVT::v8i1,   7 },
3499     { ISD::AND,  MVT::v16i1,  9 },
3500     { ISD::AND,  MVT::v32i1, 11 },
3501     { ISD::AND,  MVT::v64i1, 13 },
3502     { ISD::OR,   MVT::v2i1,   3 },
3503     { ISD::OR,   MVT::v4i1,   5 },
3504     { ISD::OR,   MVT::v8i1,   7 },
3505     { ISD::OR,   MVT::v16i1,  9 },
3506     { ISD::OR,   MVT::v32i1, 11 },
3507     { ISD::OR,   MVT::v64i1, 13 },
3508   };
3509 
3510   static const CostTblEntry AVX2BoolReduction[] = {
3511     { ISD::AND,  MVT::v16i16,  2 }, // vpmovmskb + cmp
3512     { ISD::AND,  MVT::v32i8,   2 }, // vpmovmskb + cmp
3513     { ISD::OR,   MVT::v16i16,  2 }, // vpmovmskb + cmp
3514     { ISD::OR,   MVT::v32i8,   2 }, // vpmovmskb + cmp
3515   };
3516 
3517   static const CostTblEntry AVX1BoolReduction[] = {
3518     { ISD::AND,  MVT::v4i64,   2 }, // vmovmskpd + cmp
3519     { ISD::AND,  MVT::v8i32,   2 }, // vmovmskps + cmp
3520     { ISD::AND,  MVT::v16i16,  4 }, // vextractf128 + vpand + vpmovmskb + cmp
3521     { ISD::AND,  MVT::v32i8,   4 }, // vextractf128 + vpand + vpmovmskb + cmp
3522     { ISD::OR,   MVT::v4i64,   2 }, // vmovmskpd + cmp
3523     { ISD::OR,   MVT::v8i32,   2 }, // vmovmskps + cmp
3524     { ISD::OR,   MVT::v16i16,  4 }, // vextractf128 + vpor + vpmovmskb + cmp
3525     { ISD::OR,   MVT::v32i8,   4 }, // vextractf128 + vpor + vpmovmskb + cmp
3526   };
3527 
3528   static const CostTblEntry SSE2BoolReduction[] = {
3529     { ISD::AND,  MVT::v2i64,   2 }, // movmskpd + cmp
3530     { ISD::AND,  MVT::v4i32,   2 }, // movmskps + cmp
3531     { ISD::AND,  MVT::v8i16,   2 }, // pmovmskb + cmp
3532     { ISD::AND,  MVT::v16i8,   2 }, // pmovmskb + cmp
3533     { ISD::OR,   MVT::v2i64,   2 }, // movmskpd + cmp
3534     { ISD::OR,   MVT::v4i32,   2 }, // movmskps + cmp
3535     { ISD::OR,   MVT::v8i16,   2 }, // pmovmskb + cmp
3536     { ISD::OR,   MVT::v16i8,   2 }, // pmovmskb + cmp
3537   };
3538 
3539   // Handle bool allof/anyof patterns.
3540   if (ValVTy->getElementType()->isIntegerTy(1)) {
3541     InstructionCost ArithmeticCost = 0;
3542     if (LT.first != 1 && MTy.isVector() &&
3543         MTy.getVectorNumElements() < ValVTy->getNumElements()) {
3544       // Type needs to be split. We need LT.first - 1 arithmetic ops.
3545       auto *SingleOpTy = FixedVectorType::get(ValVTy->getElementType(),
3546                                               MTy.getVectorNumElements());
3547       ArithmeticCost = getArithmeticInstrCost(Opcode, SingleOpTy, CostKind);
3548       ArithmeticCost *= LT.first - 1;
3549     }
3550 
3551     if (ST->hasAVX512())
3552       if (const auto *Entry = CostTableLookup(AVX512BoolReduction, ISD, MTy))
3553         return ArithmeticCost + Entry->Cost;
3554     if (ST->hasAVX2())
3555       if (const auto *Entry = CostTableLookup(AVX2BoolReduction, ISD, MTy))
3556         return ArithmeticCost + Entry->Cost;
3557     if (ST->hasAVX())
3558       if (const auto *Entry = CostTableLookup(AVX1BoolReduction, ISD, MTy))
3559         return ArithmeticCost + Entry->Cost;
3560     if (ST->hasSSE2())
3561       if (const auto *Entry = CostTableLookup(SSE2BoolReduction, ISD, MTy))
3562         return ArithmeticCost + Entry->Cost;
3563 
3564     return BaseT::getArithmeticReductionCost(Opcode, ValVTy, IsPairwise,
3565                                              CostKind);
3566   }
3567 
3568   unsigned NumVecElts = ValVTy->getNumElements();
3569   unsigned ScalarSize = ValVTy->getScalarSizeInBits();
3570 
3571   // Special case power of 2 reductions where the scalar type isn't changed
3572   // by type legalization.
3573   if (!isPowerOf2_32(NumVecElts) || ScalarSize != MTy.getScalarSizeInBits())
3574     return BaseT::getArithmeticReductionCost(Opcode, ValVTy, IsPairwise,
3575                                              CostKind);
3576 
3577   InstructionCost ReductionCost = 0;
3578 
3579   auto *Ty = ValVTy;
3580   if (LT.first != 1 && MTy.isVector() &&
3581       MTy.getVectorNumElements() < ValVTy->getNumElements()) {
3582     // Type needs to be split. We need LT.first - 1 arithmetic ops.
3583     Ty = FixedVectorType::get(ValVTy->getElementType(),
3584                               MTy.getVectorNumElements());
3585     ReductionCost = getArithmeticInstrCost(Opcode, Ty, CostKind);
3586     ReductionCost *= LT.first - 1;
3587     NumVecElts = MTy.getVectorNumElements();
3588   }
3589 
3590   // Now handle reduction with the legal type, taking into account size changes
3591   // at each level.
3592   while (NumVecElts > 1) {
3593     // Determine the size of the remaining vector we need to reduce.
3594     unsigned Size = NumVecElts * ScalarSize;
3595     NumVecElts /= 2;
3596     // If we're reducing from 256/512 bits, use an extract_subvector.
3597     if (Size > 128) {
3598       auto *SubTy = FixedVectorType::get(ValVTy->getElementType(), NumVecElts);
3599       ReductionCost +=
3600           getShuffleCost(TTI::SK_ExtractSubvector, Ty, None, NumVecElts, SubTy);
3601       Ty = SubTy;
3602     } else if (Size == 128) {
3603       // Reducing from 128 bits is a permute of v2f64/v2i64.
3604       FixedVectorType *ShufTy;
3605       if (ValVTy->isFloatingPointTy())
3606         ShufTy =
3607             FixedVectorType::get(Type::getDoubleTy(ValVTy->getContext()), 2);
3608       else
3609         ShufTy =
3610             FixedVectorType::get(Type::getInt64Ty(ValVTy->getContext()), 2);
3611       ReductionCost +=
3612           getShuffleCost(TTI::SK_PermuteSingleSrc, ShufTy, None, 0, nullptr);
3613     } else if (Size == 64) {
3614       // Reducing from 64 bits is a shuffle of v4f32/v4i32.
3615       FixedVectorType *ShufTy;
3616       if (ValVTy->isFloatingPointTy())
3617         ShufTy =
3618             FixedVectorType::get(Type::getFloatTy(ValVTy->getContext()), 4);
3619       else
3620         ShufTy =
3621             FixedVectorType::get(Type::getInt32Ty(ValVTy->getContext()), 4);
3622       ReductionCost +=
3623           getShuffleCost(TTI::SK_PermuteSingleSrc, ShufTy, None, 0, nullptr);
3624     } else {
3625       // Reducing from smaller size is a shift by immediate.
3626       auto *ShiftTy = FixedVectorType::get(
3627           Type::getIntNTy(ValVTy->getContext(), Size), 128 / Size);
3628       ReductionCost += getArithmeticInstrCost(
3629           Instruction::LShr, ShiftTy, CostKind,
3630           TargetTransformInfo::OK_AnyValue,
3631           TargetTransformInfo::OK_UniformConstantValue,
3632           TargetTransformInfo::OP_None, TargetTransformInfo::OP_None);
3633     }
3634 
3635     // Add the arithmetic op for this level.
3636     ReductionCost += getArithmeticInstrCost(Opcode, Ty, CostKind);
3637   }
3638 
3639   // Add the final extract element to the cost.
3640   return ReductionCost + getVectorInstrCost(Instruction::ExtractElement, Ty, 0);
3641 }
3642 
3643 InstructionCost X86TTIImpl::getMinMaxCost(Type *Ty, Type *CondTy,
3644                                           bool IsUnsigned) {
3645   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
3646 
3647   MVT MTy = LT.second;
3648 
3649   int ISD;
3650   if (Ty->isIntOrIntVectorTy()) {
3651     ISD = IsUnsigned ? ISD::UMIN : ISD::SMIN;
3652   } else {
3653     assert(Ty->isFPOrFPVectorTy() &&
3654            "Expected float point or integer vector type.");
3655     ISD = ISD::FMINNUM;
3656   }
3657 
3658   static const CostTblEntry SSE1CostTbl[] = {
3659     {ISD::FMINNUM, MVT::v4f32, 1},
3660   };
3661 
3662   static const CostTblEntry SSE2CostTbl[] = {
3663     {ISD::FMINNUM, MVT::v2f64, 1},
3664     {ISD::SMIN,    MVT::v8i16, 1},
3665     {ISD::UMIN,    MVT::v16i8, 1},
3666   };
3667 
3668   static const CostTblEntry SSE41CostTbl[] = {
3669     {ISD::SMIN,    MVT::v4i32, 1},
3670     {ISD::UMIN,    MVT::v4i32, 1},
3671     {ISD::UMIN,    MVT::v8i16, 1},
3672     {ISD::SMIN,    MVT::v16i8, 1},
3673   };
3674 
3675   static const CostTblEntry SSE42CostTbl[] = {
3676     {ISD::UMIN,    MVT::v2i64, 3}, // xor+pcmpgtq+blendvpd
3677   };
3678 
3679   static const CostTblEntry AVX1CostTbl[] = {
3680     {ISD::FMINNUM, MVT::v8f32,  1},
3681     {ISD::FMINNUM, MVT::v4f64,  1},
3682     {ISD::SMIN,    MVT::v8i32,  3},
3683     {ISD::UMIN,    MVT::v8i32,  3},
3684     {ISD::SMIN,    MVT::v16i16, 3},
3685     {ISD::UMIN,    MVT::v16i16, 3},
3686     {ISD::SMIN,    MVT::v32i8,  3},
3687     {ISD::UMIN,    MVT::v32i8,  3},
3688   };
3689 
3690   static const CostTblEntry AVX2CostTbl[] = {
3691     {ISD::SMIN,    MVT::v8i32,  1},
3692     {ISD::UMIN,    MVT::v8i32,  1},
3693     {ISD::SMIN,    MVT::v16i16, 1},
3694     {ISD::UMIN,    MVT::v16i16, 1},
3695     {ISD::SMIN,    MVT::v32i8,  1},
3696     {ISD::UMIN,    MVT::v32i8,  1},
3697   };
3698 
3699   static const CostTblEntry AVX512CostTbl[] = {
3700     {ISD::FMINNUM, MVT::v16f32, 1},
3701     {ISD::FMINNUM, MVT::v8f64,  1},
3702     {ISD::SMIN,    MVT::v2i64,  1},
3703     {ISD::UMIN,    MVT::v2i64,  1},
3704     {ISD::SMIN,    MVT::v4i64,  1},
3705     {ISD::UMIN,    MVT::v4i64,  1},
3706     {ISD::SMIN,    MVT::v8i64,  1},
3707     {ISD::UMIN,    MVT::v8i64,  1},
3708     {ISD::SMIN,    MVT::v16i32, 1},
3709     {ISD::UMIN,    MVT::v16i32, 1},
3710   };
3711 
3712   static const CostTblEntry AVX512BWCostTbl[] = {
3713     {ISD::SMIN,    MVT::v32i16, 1},
3714     {ISD::UMIN,    MVT::v32i16, 1},
3715     {ISD::SMIN,    MVT::v64i8,  1},
3716     {ISD::UMIN,    MVT::v64i8,  1},
3717   };
3718 
3719   // If we have a native MIN/MAX instruction for this type, use it.
3720   if (ST->hasBWI())
3721     if (const auto *Entry = CostTableLookup(AVX512BWCostTbl, ISD, MTy))
3722       return LT.first * Entry->Cost;
3723 
3724   if (ST->hasAVX512())
3725     if (const auto *Entry = CostTableLookup(AVX512CostTbl, ISD, MTy))
3726       return LT.first * Entry->Cost;
3727 
3728   if (ST->hasAVX2())
3729     if (const auto *Entry = CostTableLookup(AVX2CostTbl, ISD, MTy))
3730       return LT.first * Entry->Cost;
3731 
3732   if (ST->hasAVX())
3733     if (const auto *Entry = CostTableLookup(AVX1CostTbl, ISD, MTy))
3734       return LT.first * Entry->Cost;
3735 
3736   if (ST->hasSSE42())
3737     if (const auto *Entry = CostTableLookup(SSE42CostTbl, ISD, MTy))
3738       return LT.first * Entry->Cost;
3739 
3740   if (ST->hasSSE41())
3741     if (const auto *Entry = CostTableLookup(SSE41CostTbl, ISD, MTy))
3742       return LT.first * Entry->Cost;
3743 
3744   if (ST->hasSSE2())
3745     if (const auto *Entry = CostTableLookup(SSE2CostTbl, ISD, MTy))
3746       return LT.first * Entry->Cost;
3747 
3748   if (ST->hasSSE1())
3749     if (const auto *Entry = CostTableLookup(SSE1CostTbl, ISD, MTy))
3750       return LT.first * Entry->Cost;
3751 
3752   unsigned CmpOpcode;
3753   if (Ty->isFPOrFPVectorTy()) {
3754     CmpOpcode = Instruction::FCmp;
3755   } else {
3756     assert(Ty->isIntOrIntVectorTy() &&
3757            "expecting floating point or integer type for min/max reduction");
3758     CmpOpcode = Instruction::ICmp;
3759   }
3760 
3761   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
3762   // Otherwise fall back to cmp+select.
3763   InstructionCost Result =
3764       getCmpSelInstrCost(CmpOpcode, Ty, CondTy, CmpInst::BAD_ICMP_PREDICATE,
3765                          CostKind) +
3766       getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
3767                          CmpInst::BAD_ICMP_PREDICATE, CostKind);
3768   return Result;
3769 }
3770 
3771 InstructionCost
3772 X86TTIImpl::getMinMaxReductionCost(VectorType *ValTy, VectorType *CondTy,
3773                                    bool IsPairwise, bool IsUnsigned,
3774                                    TTI::TargetCostKind CostKind) {
3775   // Just use the default implementation for pair reductions.
3776   if (IsPairwise)
3777     return BaseT::getMinMaxReductionCost(ValTy, CondTy, IsPairwise, IsUnsigned,
3778                                          CostKind);
3779 
3780   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
3781 
3782   MVT MTy = LT.second;
3783 
3784   int ISD;
3785   if (ValTy->isIntOrIntVectorTy()) {
3786     ISD = IsUnsigned ? ISD::UMIN : ISD::SMIN;
3787   } else {
3788     assert(ValTy->isFPOrFPVectorTy() &&
3789            "Expected float point or integer vector type.");
3790     ISD = ISD::FMINNUM;
3791   }
3792 
3793   // We use the Intel Architecture Code Analyzer(IACA) to measure the throughput
3794   // and make it as the cost.
3795 
3796   static const CostTblEntry SSE2CostTblNoPairWise[] = {
3797       {ISD::UMIN, MVT::v2i16, 5}, // need pxors to use pminsw/pmaxsw
3798       {ISD::UMIN, MVT::v4i16, 7}, // need pxors to use pminsw/pmaxsw
3799       {ISD::UMIN, MVT::v8i16, 9}, // need pxors to use pminsw/pmaxsw
3800   };
3801 
3802   static const CostTblEntry SSE41CostTblNoPairWise[] = {
3803       {ISD::SMIN, MVT::v2i16, 3}, // same as sse2
3804       {ISD::SMIN, MVT::v4i16, 5}, // same as sse2
3805       {ISD::UMIN, MVT::v2i16, 5}, // same as sse2
3806       {ISD::UMIN, MVT::v4i16, 7}, // same as sse2
3807       {ISD::SMIN, MVT::v8i16, 4}, // phminposuw+xor
3808       {ISD::UMIN, MVT::v8i16, 4}, // FIXME: umin is cheaper than umax
3809       {ISD::SMIN, MVT::v2i8,  3}, // pminsb
3810       {ISD::SMIN, MVT::v4i8,  5}, // pminsb
3811       {ISD::SMIN, MVT::v8i8,  7}, // pminsb
3812       {ISD::SMIN, MVT::v16i8, 6},
3813       {ISD::UMIN, MVT::v2i8,  3}, // same as sse2
3814       {ISD::UMIN, MVT::v4i8,  5}, // same as sse2
3815       {ISD::UMIN, MVT::v8i8,  7}, // same as sse2
3816       {ISD::UMIN, MVT::v16i8, 6}, // FIXME: umin is cheaper than umax
3817   };
3818 
3819   static const CostTblEntry AVX1CostTblNoPairWise[] = {
3820       {ISD::SMIN, MVT::v16i16, 6},
3821       {ISD::UMIN, MVT::v16i16, 6}, // FIXME: umin is cheaper than umax
3822       {ISD::SMIN, MVT::v32i8, 8},
3823       {ISD::UMIN, MVT::v32i8, 8},
3824   };
3825 
3826   static const CostTblEntry AVX512BWCostTblNoPairWise[] = {
3827       {ISD::SMIN, MVT::v32i16, 8},
3828       {ISD::UMIN, MVT::v32i16, 8}, // FIXME: umin is cheaper than umax
3829       {ISD::SMIN, MVT::v64i8, 10},
3830       {ISD::UMIN, MVT::v64i8, 10},
3831   };
3832 
3833   // Before legalizing the type, give a chance to look up illegal narrow types
3834   // in the table.
3835   // FIXME: Is there a better way to do this?
3836   EVT VT = TLI->getValueType(DL, ValTy);
3837   if (VT.isSimple()) {
3838     MVT MTy = VT.getSimpleVT();
3839     if (ST->hasBWI())
3840       if (const auto *Entry = CostTableLookup(AVX512BWCostTblNoPairWise, ISD, MTy))
3841         return Entry->Cost;
3842 
3843     if (ST->hasAVX())
3844       if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
3845         return Entry->Cost;
3846 
3847     if (ST->hasSSE41())
3848       if (const auto *Entry = CostTableLookup(SSE41CostTblNoPairWise, ISD, MTy))
3849         return Entry->Cost;
3850 
3851     if (ST->hasSSE2())
3852       if (const auto *Entry = CostTableLookup(SSE2CostTblNoPairWise, ISD, MTy))
3853         return Entry->Cost;
3854   }
3855 
3856   auto *ValVTy = cast<FixedVectorType>(ValTy);
3857   unsigned NumVecElts = ValVTy->getNumElements();
3858 
3859   auto *Ty = ValVTy;
3860   InstructionCost MinMaxCost = 0;
3861   if (LT.first != 1 && MTy.isVector() &&
3862       MTy.getVectorNumElements() < ValVTy->getNumElements()) {
3863     // Type needs to be split. We need LT.first - 1 operations ops.
3864     Ty = FixedVectorType::get(ValVTy->getElementType(),
3865                               MTy.getVectorNumElements());
3866     auto *SubCondTy = FixedVectorType::get(CondTy->getElementType(),
3867                                            MTy.getVectorNumElements());
3868     MinMaxCost = getMinMaxCost(Ty, SubCondTy, IsUnsigned);
3869     MinMaxCost *= LT.first - 1;
3870     NumVecElts = MTy.getVectorNumElements();
3871   }
3872 
3873   if (ST->hasBWI())
3874     if (const auto *Entry = CostTableLookup(AVX512BWCostTblNoPairWise, ISD, MTy))
3875       return MinMaxCost + Entry->Cost;
3876 
3877   if (ST->hasAVX())
3878     if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
3879       return MinMaxCost + Entry->Cost;
3880 
3881   if (ST->hasSSE41())
3882     if (const auto *Entry = CostTableLookup(SSE41CostTblNoPairWise, ISD, MTy))
3883       return MinMaxCost + Entry->Cost;
3884 
3885   if (ST->hasSSE2())
3886     if (const auto *Entry = CostTableLookup(SSE2CostTblNoPairWise, ISD, MTy))
3887       return MinMaxCost + Entry->Cost;
3888 
3889   unsigned ScalarSize = ValTy->getScalarSizeInBits();
3890 
3891   // Special case power of 2 reductions where the scalar type isn't changed
3892   // by type legalization.
3893   if (!isPowerOf2_32(ValVTy->getNumElements()) ||
3894       ScalarSize != MTy.getScalarSizeInBits())
3895     return BaseT::getMinMaxReductionCost(ValTy, CondTy, IsPairwise, IsUnsigned,
3896                                          CostKind);
3897 
3898   // Now handle reduction with the legal type, taking into account size changes
3899   // at each level.
3900   while (NumVecElts > 1) {
3901     // Determine the size of the remaining vector we need to reduce.
3902     unsigned Size = NumVecElts * ScalarSize;
3903     NumVecElts /= 2;
3904     // If we're reducing from 256/512 bits, use an extract_subvector.
3905     if (Size > 128) {
3906       auto *SubTy = FixedVectorType::get(ValVTy->getElementType(), NumVecElts);
3907       MinMaxCost +=
3908           getShuffleCost(TTI::SK_ExtractSubvector, Ty, None, NumVecElts, SubTy);
3909       Ty = SubTy;
3910     } else if (Size == 128) {
3911       // Reducing from 128 bits is a permute of v2f64/v2i64.
3912       VectorType *ShufTy;
3913       if (ValTy->isFloatingPointTy())
3914         ShufTy =
3915             FixedVectorType::get(Type::getDoubleTy(ValTy->getContext()), 2);
3916       else
3917         ShufTy = FixedVectorType::get(Type::getInt64Ty(ValTy->getContext()), 2);
3918       MinMaxCost +=
3919           getShuffleCost(TTI::SK_PermuteSingleSrc, ShufTy, None, 0, nullptr);
3920     } else if (Size == 64) {
3921       // Reducing from 64 bits is a shuffle of v4f32/v4i32.
3922       FixedVectorType *ShufTy;
3923       if (ValTy->isFloatingPointTy())
3924         ShufTy = FixedVectorType::get(Type::getFloatTy(ValTy->getContext()), 4);
3925       else
3926         ShufTy = FixedVectorType::get(Type::getInt32Ty(ValTy->getContext()), 4);
3927       MinMaxCost +=
3928           getShuffleCost(TTI::SK_PermuteSingleSrc, ShufTy, None, 0, nullptr);
3929     } else {
3930       // Reducing from smaller size is a shift by immediate.
3931       auto *ShiftTy = FixedVectorType::get(
3932           Type::getIntNTy(ValTy->getContext(), Size), 128 / Size);
3933       MinMaxCost += getArithmeticInstrCost(
3934           Instruction::LShr, ShiftTy, TTI::TCK_RecipThroughput,
3935           TargetTransformInfo::OK_AnyValue,
3936           TargetTransformInfo::OK_UniformConstantValue,
3937           TargetTransformInfo::OP_None, TargetTransformInfo::OP_None);
3938     }
3939 
3940     // Add the arithmetic op for this level.
3941     auto *SubCondTy =
3942         FixedVectorType::get(CondTy->getElementType(), Ty->getNumElements());
3943     MinMaxCost += getMinMaxCost(Ty, SubCondTy, IsUnsigned);
3944   }
3945 
3946   // Add the final extract element to the cost.
3947   return MinMaxCost + getVectorInstrCost(Instruction::ExtractElement, Ty, 0);
3948 }
3949 
3950 /// Calculate the cost of materializing a 64-bit value. This helper
3951 /// method might only calculate a fraction of a larger immediate. Therefore it
3952 /// is valid to return a cost of ZERO.
3953 InstructionCost X86TTIImpl::getIntImmCost(int64_t Val) {
3954   if (Val == 0)
3955     return TTI::TCC_Free;
3956 
3957   if (isInt<32>(Val))
3958     return TTI::TCC_Basic;
3959 
3960   return 2 * TTI::TCC_Basic;
3961 }
3962 
3963 InstructionCost X86TTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
3964                                           TTI::TargetCostKind CostKind) {
3965   assert(Ty->isIntegerTy());
3966 
3967   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3968   if (BitSize == 0)
3969     return ~0U;
3970 
3971   // Never hoist constants larger than 128bit, because this might lead to
3972   // incorrect code generation or assertions in codegen.
3973   // Fixme: Create a cost model for types larger than i128 once the codegen
3974   // issues have been fixed.
3975   if (BitSize > 128)
3976     return TTI::TCC_Free;
3977 
3978   if (Imm == 0)
3979     return TTI::TCC_Free;
3980 
3981   // Sign-extend all constants to a multiple of 64-bit.
3982   APInt ImmVal = Imm;
3983   if (BitSize % 64 != 0)
3984     ImmVal = Imm.sext(alignTo(BitSize, 64));
3985 
3986   // Split the constant into 64-bit chunks and calculate the cost for each
3987   // chunk.
3988   InstructionCost Cost = 0;
3989   for (unsigned ShiftVal = 0; ShiftVal < BitSize; ShiftVal += 64) {
3990     APInt Tmp = ImmVal.ashr(ShiftVal).sextOrTrunc(64);
3991     int64_t Val = Tmp.getSExtValue();
3992     Cost += getIntImmCost(Val);
3993   }
3994   // We need at least one instruction to materialize the constant.
3995   return std::max<InstructionCost>(1, Cost);
3996 }
3997 
3998 InstructionCost X86TTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
3999                                               const APInt &Imm, Type *Ty,
4000                                               TTI::TargetCostKind CostKind,
4001                                               Instruction *Inst) {
4002   assert(Ty->isIntegerTy());
4003 
4004   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4005   // There is no cost model for constants with a bit size of 0. Return TCC_Free
4006   // here, so that constant hoisting will ignore this constant.
4007   if (BitSize == 0)
4008     return TTI::TCC_Free;
4009 
4010   unsigned ImmIdx = ~0U;
4011   switch (Opcode) {
4012   default:
4013     return TTI::TCC_Free;
4014   case Instruction::GetElementPtr:
4015     // Always hoist the base address of a GetElementPtr. This prevents the
4016     // creation of new constants for every base constant that gets constant
4017     // folded with the offset.
4018     if (Idx == 0)
4019       return 2 * TTI::TCC_Basic;
4020     return TTI::TCC_Free;
4021   case Instruction::Store:
4022     ImmIdx = 0;
4023     break;
4024   case Instruction::ICmp:
4025     // This is an imperfect hack to prevent constant hoisting of
4026     // compares that might be trying to check if a 64-bit value fits in
4027     // 32-bits. The backend can optimize these cases using a right shift by 32.
4028     // Ideally we would check the compare predicate here. There also other
4029     // similar immediates the backend can use shifts for.
4030     if (Idx == 1 && Imm.getBitWidth() == 64) {
4031       uint64_t ImmVal = Imm.getZExtValue();
4032       if (ImmVal == 0x100000000ULL || ImmVal == 0xffffffff)
4033         return TTI::TCC_Free;
4034     }
4035     ImmIdx = 1;
4036     break;
4037   case Instruction::And:
4038     // We support 64-bit ANDs with immediates with 32-bits of leading zeroes
4039     // by using a 32-bit operation with implicit zero extension. Detect such
4040     // immediates here as the normal path expects bit 31 to be sign extended.
4041     if (Idx == 1 && Imm.getBitWidth() == 64 && isUInt<32>(Imm.getZExtValue()))
4042       return TTI::TCC_Free;
4043     ImmIdx = 1;
4044     break;
4045   case Instruction::Add:
4046   case Instruction::Sub:
4047     // For add/sub, we can use the opposite instruction for INT32_MIN.
4048     if (Idx == 1 && Imm.getBitWidth() == 64 && Imm.getZExtValue() == 0x80000000)
4049       return TTI::TCC_Free;
4050     ImmIdx = 1;
4051     break;
4052   case Instruction::UDiv:
4053   case Instruction::SDiv:
4054   case Instruction::URem:
4055   case Instruction::SRem:
4056     // Division by constant is typically expanded later into a different
4057     // instruction sequence. This completely changes the constants.
4058     // Report them as "free" to stop ConstantHoist from marking them as opaque.
4059     return TTI::TCC_Free;
4060   case Instruction::Mul:
4061   case Instruction::Or:
4062   case Instruction::Xor:
4063     ImmIdx = 1;
4064     break;
4065   // Always return TCC_Free for the shift value of a shift instruction.
4066   case Instruction::Shl:
4067   case Instruction::LShr:
4068   case Instruction::AShr:
4069     if (Idx == 1)
4070       return TTI::TCC_Free;
4071     break;
4072   case Instruction::Trunc:
4073   case Instruction::ZExt:
4074   case Instruction::SExt:
4075   case Instruction::IntToPtr:
4076   case Instruction::PtrToInt:
4077   case Instruction::BitCast:
4078   case Instruction::PHI:
4079   case Instruction::Call:
4080   case Instruction::Select:
4081   case Instruction::Ret:
4082   case Instruction::Load:
4083     break;
4084   }
4085 
4086   if (Idx == ImmIdx) {
4087     int NumConstants = divideCeil(BitSize, 64);
4088     InstructionCost Cost = X86TTIImpl::getIntImmCost(Imm, Ty, CostKind);
4089     return (Cost <= NumConstants * TTI::TCC_Basic)
4090                ? static_cast<int>(TTI::TCC_Free)
4091                : Cost;
4092   }
4093 
4094   return X86TTIImpl::getIntImmCost(Imm, Ty, CostKind);
4095 }
4096 
4097 InstructionCost X86TTIImpl::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
4098                                                 const APInt &Imm, Type *Ty,
4099                                                 TTI::TargetCostKind CostKind) {
4100   assert(Ty->isIntegerTy());
4101 
4102   unsigned BitSize = Ty->getPrimitiveSizeInBits();
4103   // There is no cost model for constants with a bit size of 0. Return TCC_Free
4104   // here, so that constant hoisting will ignore this constant.
4105   if (BitSize == 0)
4106     return TTI::TCC_Free;
4107 
4108   switch (IID) {
4109   default:
4110     return TTI::TCC_Free;
4111   case Intrinsic::sadd_with_overflow:
4112   case Intrinsic::uadd_with_overflow:
4113   case Intrinsic::ssub_with_overflow:
4114   case Intrinsic::usub_with_overflow:
4115   case Intrinsic::smul_with_overflow:
4116   case Intrinsic::umul_with_overflow:
4117     if ((Idx == 1) && Imm.getBitWidth() <= 64 && isInt<32>(Imm.getSExtValue()))
4118       return TTI::TCC_Free;
4119     break;
4120   case Intrinsic::experimental_stackmap:
4121     if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
4122       return TTI::TCC_Free;
4123     break;
4124   case Intrinsic::experimental_patchpoint_void:
4125   case Intrinsic::experimental_patchpoint_i64:
4126     if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
4127       return TTI::TCC_Free;
4128     break;
4129   }
4130   return X86TTIImpl::getIntImmCost(Imm, Ty, CostKind);
4131 }
4132 
4133 InstructionCost X86TTIImpl::getCFInstrCost(unsigned Opcode,
4134                                            TTI::TargetCostKind CostKind,
4135                                            const Instruction *I) {
4136   if (CostKind != TTI::TCK_RecipThroughput)
4137     return Opcode == Instruction::PHI ? 0 : 1;
4138   // Branches are assumed to be predicted.
4139   return 0;
4140 }
4141 
4142 int X86TTIImpl::getGatherOverhead() const {
4143   // Some CPUs have more overhead for gather. The specified overhead is relative
4144   // to the Load operation. "2" is the number provided by Intel architects. This
4145   // parameter is used for cost estimation of Gather Op and comparison with
4146   // other alternatives.
4147   // TODO: Remove the explicit hasAVX512()?, That would mean we would only
4148   // enable gather with a -march.
4149   if (ST->hasAVX512() || (ST->hasAVX2() && ST->hasFastGather()))
4150     return 2;
4151 
4152   return 1024;
4153 }
4154 
4155 int X86TTIImpl::getScatterOverhead() const {
4156   if (ST->hasAVX512())
4157     return 2;
4158 
4159   return 1024;
4160 }
4161 
4162 // Return an average cost of Gather / Scatter instruction, maybe improved later.
4163 // FIXME: Add TargetCostKind support.
4164 InstructionCost X86TTIImpl::getGSVectorCost(unsigned Opcode, Type *SrcVTy,
4165                                             const Value *Ptr, Align Alignment,
4166                                             unsigned AddressSpace) {
4167 
4168   assert(isa<VectorType>(SrcVTy) && "Unexpected type in getGSVectorCost");
4169   unsigned VF = cast<FixedVectorType>(SrcVTy)->getNumElements();
4170 
4171   // Try to reduce index size from 64 bit (default for GEP)
4172   // to 32. It is essential for VF 16. If the index can't be reduced to 32, the
4173   // operation will use 16 x 64 indices which do not fit in a zmm and needs
4174   // to split. Also check that the base pointer is the same for all lanes,
4175   // and that there's at most one variable index.
4176   auto getIndexSizeInBits = [](const Value *Ptr, const DataLayout &DL) {
4177     unsigned IndexSize = DL.getPointerSizeInBits();
4178     const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4179     if (IndexSize < 64 || !GEP)
4180       return IndexSize;
4181 
4182     unsigned NumOfVarIndices = 0;
4183     const Value *Ptrs = GEP->getPointerOperand();
4184     if (Ptrs->getType()->isVectorTy() && !getSplatValue(Ptrs))
4185       return IndexSize;
4186     for (unsigned i = 1; i < GEP->getNumOperands(); ++i) {
4187       if (isa<Constant>(GEP->getOperand(i)))
4188         continue;
4189       Type *IndxTy = GEP->getOperand(i)->getType();
4190       if (auto *IndexVTy = dyn_cast<VectorType>(IndxTy))
4191         IndxTy = IndexVTy->getElementType();
4192       if ((IndxTy->getPrimitiveSizeInBits() == 64 &&
4193           !isa<SExtInst>(GEP->getOperand(i))) ||
4194          ++NumOfVarIndices > 1)
4195         return IndexSize; // 64
4196     }
4197     return (unsigned)32;
4198   };
4199 
4200   // Trying to reduce IndexSize to 32 bits for vector 16.
4201   // By default the IndexSize is equal to pointer size.
4202   unsigned IndexSize = (ST->hasAVX512() && VF >= 16)
4203                            ? getIndexSizeInBits(Ptr, DL)
4204                            : DL.getPointerSizeInBits();
4205 
4206   auto *IndexVTy = FixedVectorType::get(
4207       IntegerType::get(SrcVTy->getContext(), IndexSize), VF);
4208   std::pair<InstructionCost, MVT> IdxsLT =
4209       TLI->getTypeLegalizationCost(DL, IndexVTy);
4210   std::pair<InstructionCost, MVT> SrcLT =
4211       TLI->getTypeLegalizationCost(DL, SrcVTy);
4212   InstructionCost::CostType SplitFactor =
4213       *std::max(IdxsLT.first, SrcLT.first).getValue();
4214   if (SplitFactor > 1) {
4215     // Handle splitting of vector of pointers
4216     auto *SplitSrcTy =
4217         FixedVectorType::get(SrcVTy->getScalarType(), VF / SplitFactor);
4218     return SplitFactor * getGSVectorCost(Opcode, SplitSrcTy, Ptr, Alignment,
4219                                          AddressSpace);
4220   }
4221 
4222   // The gather / scatter cost is given by Intel architects. It is a rough
4223   // number since we are looking at one instruction in a time.
4224   const int GSOverhead = (Opcode == Instruction::Load)
4225                              ? getGatherOverhead()
4226                              : getScatterOverhead();
4227   return GSOverhead + VF * getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
4228                                            MaybeAlign(Alignment), AddressSpace,
4229                                            TTI::TCK_RecipThroughput);
4230 }
4231 
4232 /// Return the cost of full scalarization of gather / scatter operation.
4233 ///
4234 /// Opcode - Load or Store instruction.
4235 /// SrcVTy - The type of the data vector that should be gathered or scattered.
4236 /// VariableMask - The mask is non-constant at compile time.
4237 /// Alignment - Alignment for one element.
4238 /// AddressSpace - pointer[s] address space.
4239 ///
4240 /// FIXME: Add TargetCostKind support.
4241 InstructionCost X86TTIImpl::getGSScalarCost(unsigned Opcode, Type *SrcVTy,
4242                                             bool VariableMask, Align Alignment,
4243                                             unsigned AddressSpace) {
4244   unsigned VF = cast<FixedVectorType>(SrcVTy)->getNumElements();
4245   APInt DemandedElts = APInt::getAllOnesValue(VF);
4246   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4247 
4248   InstructionCost MaskUnpackCost = 0;
4249   if (VariableMask) {
4250     auto *MaskTy =
4251         FixedVectorType::get(Type::getInt1Ty(SrcVTy->getContext()), VF);
4252     MaskUnpackCost =
4253         getScalarizationOverhead(MaskTy, DemandedElts, false, true);
4254     InstructionCost ScalarCompareCost = getCmpSelInstrCost(
4255         Instruction::ICmp, Type::getInt1Ty(SrcVTy->getContext()), nullptr,
4256         CmpInst::BAD_ICMP_PREDICATE, CostKind);
4257     InstructionCost BranchCost = getCFInstrCost(Instruction::Br, CostKind);
4258     MaskUnpackCost += VF * (BranchCost + ScalarCompareCost);
4259   }
4260 
4261   // The cost of the scalar loads/stores.
4262   InstructionCost MemoryOpCost =
4263       VF * getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
4264                            MaybeAlign(Alignment), AddressSpace, CostKind);
4265 
4266   InstructionCost InsertExtractCost = 0;
4267   if (Opcode == Instruction::Load)
4268     for (unsigned i = 0; i < VF; ++i)
4269       // Add the cost of inserting each scalar load into the vector
4270       InsertExtractCost +=
4271         getVectorInstrCost(Instruction::InsertElement, SrcVTy, i);
4272   else
4273     for (unsigned i = 0; i < VF; ++i)
4274       // Add the cost of extracting each element out of the data vector
4275       InsertExtractCost +=
4276         getVectorInstrCost(Instruction::ExtractElement, SrcVTy, i);
4277 
4278   return MemoryOpCost + MaskUnpackCost + InsertExtractCost;
4279 }
4280 
4281 /// Calculate the cost of Gather / Scatter operation
4282 InstructionCost X86TTIImpl::getGatherScatterOpCost(
4283     unsigned Opcode, Type *SrcVTy, const Value *Ptr, bool VariableMask,
4284     Align Alignment, TTI::TargetCostKind CostKind,
4285     const Instruction *I = nullptr) {
4286   if (CostKind != TTI::TCK_RecipThroughput) {
4287     if ((Opcode == Instruction::Load &&
4288          isLegalMaskedGather(SrcVTy, Align(Alignment))) ||
4289         (Opcode == Instruction::Store &&
4290          isLegalMaskedScatter(SrcVTy, Align(Alignment))))
4291       return 1;
4292     return BaseT::getGatherScatterOpCost(Opcode, SrcVTy, Ptr, VariableMask,
4293                                          Alignment, CostKind, I);
4294   }
4295 
4296   assert(SrcVTy->isVectorTy() && "Unexpected data type for Gather/Scatter");
4297   unsigned VF = cast<FixedVectorType>(SrcVTy)->getNumElements();
4298   PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
4299   if (!PtrTy && Ptr->getType()->isVectorTy())
4300     PtrTy = dyn_cast<PointerType>(
4301         cast<VectorType>(Ptr->getType())->getElementType());
4302   assert(PtrTy && "Unexpected type for Ptr argument");
4303   unsigned AddressSpace = PtrTy->getAddressSpace();
4304 
4305   bool Scalarize = false;
4306   if ((Opcode == Instruction::Load &&
4307        !isLegalMaskedGather(SrcVTy, Align(Alignment))) ||
4308       (Opcode == Instruction::Store &&
4309        !isLegalMaskedScatter(SrcVTy, Align(Alignment))))
4310     Scalarize = true;
4311   // Gather / Scatter for vector 2 is not profitable on KNL / SKX
4312   // Vector-4 of gather/scatter instruction does not exist on KNL.
4313   // We can extend it to 8 elements, but zeroing upper bits of
4314   // the mask vector will add more instructions. Right now we give the scalar
4315   // cost of vector-4 for KNL. TODO: Check, maybe the gather/scatter instruction
4316   // is better in the VariableMask case.
4317   if (ST->hasAVX512() && (VF == 2 || (VF == 4 && !ST->hasVLX())))
4318     Scalarize = true;
4319 
4320   if (Scalarize)
4321     return getGSScalarCost(Opcode, SrcVTy, VariableMask, Alignment,
4322                            AddressSpace);
4323 
4324   return getGSVectorCost(Opcode, SrcVTy, Ptr, Alignment, AddressSpace);
4325 }
4326 
4327 bool X86TTIImpl::isLSRCostLess(TargetTransformInfo::LSRCost &C1,
4328                                TargetTransformInfo::LSRCost &C2) {
4329     // X86 specific here are "instruction number 1st priority".
4330     return std::tie(C1.Insns, C1.NumRegs, C1.AddRecCost,
4331                     C1.NumIVMuls, C1.NumBaseAdds,
4332                     C1.ScaleCost, C1.ImmCost, C1.SetupCost) <
4333            std::tie(C2.Insns, C2.NumRegs, C2.AddRecCost,
4334                     C2.NumIVMuls, C2.NumBaseAdds,
4335                     C2.ScaleCost, C2.ImmCost, C2.SetupCost);
4336 }
4337 
4338 bool X86TTIImpl::canMacroFuseCmp() {
4339   return ST->hasMacroFusion() || ST->hasBranchFusion();
4340 }
4341 
4342 bool X86TTIImpl::isLegalMaskedLoad(Type *DataTy, Align Alignment) {
4343   if (!ST->hasAVX())
4344     return false;
4345 
4346   // The backend can't handle a single element vector.
4347   if (isa<VectorType>(DataTy) &&
4348       cast<FixedVectorType>(DataTy)->getNumElements() == 1)
4349     return false;
4350   Type *ScalarTy = DataTy->getScalarType();
4351 
4352   if (ScalarTy->isPointerTy())
4353     return true;
4354 
4355   if (ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
4356     return true;
4357 
4358   if (!ScalarTy->isIntegerTy())
4359     return false;
4360 
4361   unsigned IntWidth = ScalarTy->getIntegerBitWidth();
4362   return IntWidth == 32 || IntWidth == 64 ||
4363          ((IntWidth == 8 || IntWidth == 16) && ST->hasBWI());
4364 }
4365 
4366 bool X86TTIImpl::isLegalMaskedStore(Type *DataType, Align Alignment) {
4367   return isLegalMaskedLoad(DataType, Alignment);
4368 }
4369 
4370 bool X86TTIImpl::isLegalNTLoad(Type *DataType, Align Alignment) {
4371   unsigned DataSize = DL.getTypeStoreSize(DataType);
4372   // The only supported nontemporal loads are for aligned vectors of 16 or 32
4373   // bytes.  Note that 32-byte nontemporal vector loads are supported by AVX2
4374   // (the equivalent stores only require AVX).
4375   if (Alignment >= DataSize && (DataSize == 16 || DataSize == 32))
4376     return DataSize == 16 ?  ST->hasSSE1() : ST->hasAVX2();
4377 
4378   return false;
4379 }
4380 
4381 bool X86TTIImpl::isLegalNTStore(Type *DataType, Align Alignment) {
4382   unsigned DataSize = DL.getTypeStoreSize(DataType);
4383 
4384   // SSE4A supports nontemporal stores of float and double at arbitrary
4385   // alignment.
4386   if (ST->hasSSE4A() && (DataType->isFloatTy() || DataType->isDoubleTy()))
4387     return true;
4388 
4389   // Besides the SSE4A subtarget exception above, only aligned stores are
4390   // available nontemporaly on any other subtarget.  And only stores with a size
4391   // of 4..32 bytes (powers of 2, only) are permitted.
4392   if (Alignment < DataSize || DataSize < 4 || DataSize > 32 ||
4393       !isPowerOf2_32(DataSize))
4394     return false;
4395 
4396   // 32-byte vector nontemporal stores are supported by AVX (the equivalent
4397   // loads require AVX2).
4398   if (DataSize == 32)
4399     return ST->hasAVX();
4400   else if (DataSize == 16)
4401     return ST->hasSSE1();
4402   return true;
4403 }
4404 
4405 bool X86TTIImpl::isLegalMaskedExpandLoad(Type *DataTy) {
4406   if (!isa<VectorType>(DataTy))
4407     return false;
4408 
4409   if (!ST->hasAVX512())
4410     return false;
4411 
4412   // The backend can't handle a single element vector.
4413   if (cast<FixedVectorType>(DataTy)->getNumElements() == 1)
4414     return false;
4415 
4416   Type *ScalarTy = cast<VectorType>(DataTy)->getElementType();
4417 
4418   if (ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
4419     return true;
4420 
4421   if (!ScalarTy->isIntegerTy())
4422     return false;
4423 
4424   unsigned IntWidth = ScalarTy->getIntegerBitWidth();
4425   return IntWidth == 32 || IntWidth == 64 ||
4426          ((IntWidth == 8 || IntWidth == 16) && ST->hasVBMI2());
4427 }
4428 
4429 bool X86TTIImpl::isLegalMaskedCompressStore(Type *DataTy) {
4430   return isLegalMaskedExpandLoad(DataTy);
4431 }
4432 
4433 bool X86TTIImpl::isLegalMaskedGather(Type *DataTy, Align Alignment) {
4434   // Some CPUs have better gather performance than others.
4435   // TODO: Remove the explicit ST->hasAVX512()?, That would mean we would only
4436   // enable gather with a -march.
4437   if (!(ST->hasAVX512() || (ST->hasFastGather() && ST->hasAVX2())))
4438     return false;
4439 
4440   // This function is called now in two cases: from the Loop Vectorizer
4441   // and from the Scalarizer.
4442   // When the Loop Vectorizer asks about legality of the feature,
4443   // the vectorization factor is not calculated yet. The Loop Vectorizer
4444   // sends a scalar type and the decision is based on the width of the
4445   // scalar element.
4446   // Later on, the cost model will estimate usage this intrinsic based on
4447   // the vector type.
4448   // The Scalarizer asks again about legality. It sends a vector type.
4449   // In this case we can reject non-power-of-2 vectors.
4450   // We also reject single element vectors as the type legalizer can't
4451   // scalarize it.
4452   if (auto *DataVTy = dyn_cast<FixedVectorType>(DataTy)) {
4453     unsigned NumElts = DataVTy->getNumElements();
4454     if (NumElts == 1)
4455       return false;
4456   }
4457   Type *ScalarTy = DataTy->getScalarType();
4458   if (ScalarTy->isPointerTy())
4459     return true;
4460 
4461   if (ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
4462     return true;
4463 
4464   if (!ScalarTy->isIntegerTy())
4465     return false;
4466 
4467   unsigned IntWidth = ScalarTy->getIntegerBitWidth();
4468   return IntWidth == 32 || IntWidth == 64;
4469 }
4470 
4471 bool X86TTIImpl::isLegalMaskedScatter(Type *DataType, Align Alignment) {
4472   // AVX2 doesn't support scatter
4473   if (!ST->hasAVX512())
4474     return false;
4475   return isLegalMaskedGather(DataType, Alignment);
4476 }
4477 
4478 bool X86TTIImpl::hasDivRemOp(Type *DataType, bool IsSigned) {
4479   EVT VT = TLI->getValueType(DL, DataType);
4480   return TLI->isOperationLegal(IsSigned ? ISD::SDIVREM : ISD::UDIVREM, VT);
4481 }
4482 
4483 bool X86TTIImpl::isFCmpOrdCheaperThanFCmpZero(Type *Ty) {
4484   return false;
4485 }
4486 
4487 bool X86TTIImpl::areInlineCompatible(const Function *Caller,
4488                                      const Function *Callee) const {
4489   const TargetMachine &TM = getTLI()->getTargetMachine();
4490 
4491   // Work this as a subsetting of subtarget features.
4492   const FeatureBitset &CallerBits =
4493       TM.getSubtargetImpl(*Caller)->getFeatureBits();
4494   const FeatureBitset &CalleeBits =
4495       TM.getSubtargetImpl(*Callee)->getFeatureBits();
4496 
4497   FeatureBitset RealCallerBits = CallerBits & ~InlineFeatureIgnoreList;
4498   FeatureBitset RealCalleeBits = CalleeBits & ~InlineFeatureIgnoreList;
4499   return (RealCallerBits & RealCalleeBits) == RealCalleeBits;
4500 }
4501 
4502 bool X86TTIImpl::areFunctionArgsABICompatible(
4503     const Function *Caller, const Function *Callee,
4504     SmallPtrSetImpl<Argument *> &Args) const {
4505   if (!BaseT::areFunctionArgsABICompatible(Caller, Callee, Args))
4506     return false;
4507 
4508   // If we get here, we know the target features match. If one function
4509   // considers 512-bit vectors legal and the other does not, consider them
4510   // incompatible.
4511   const TargetMachine &TM = getTLI()->getTargetMachine();
4512 
4513   if (TM.getSubtarget<X86Subtarget>(*Caller).useAVX512Regs() ==
4514       TM.getSubtarget<X86Subtarget>(*Callee).useAVX512Regs())
4515     return true;
4516 
4517   // Consider the arguments compatible if they aren't vectors or aggregates.
4518   // FIXME: Look at the size of vectors.
4519   // FIXME: Look at the element types of aggregates to see if there are vectors.
4520   // FIXME: The API of this function seems intended to allow arguments
4521   // to be removed from the set, but the caller doesn't check if the set
4522   // becomes empty so that may not work in practice.
4523   return llvm::none_of(Args, [](Argument *A) {
4524     auto *EltTy = cast<PointerType>(A->getType())->getElementType();
4525     return EltTy->isVectorTy() || EltTy->isAggregateType();
4526   });
4527 }
4528 
4529 X86TTIImpl::TTI::MemCmpExpansionOptions
4530 X86TTIImpl::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const {
4531   TTI::MemCmpExpansionOptions Options;
4532   Options.MaxNumLoads = TLI->getMaxExpandSizeMemcmp(OptSize);
4533   Options.NumLoadsPerBlock = 2;
4534   // All GPR and vector loads can be unaligned.
4535   Options.AllowOverlappingLoads = true;
4536   if (IsZeroCmp) {
4537     // Only enable vector loads for equality comparison. Right now the vector
4538     // version is not as fast for three way compare (see #33329).
4539     const unsigned PreferredWidth = ST->getPreferVectorWidth();
4540     if (PreferredWidth >= 512 && ST->hasAVX512()) Options.LoadSizes.push_back(64);
4541     if (PreferredWidth >= 256 && ST->hasAVX()) Options.LoadSizes.push_back(32);
4542     if (PreferredWidth >= 128 && ST->hasSSE2()) Options.LoadSizes.push_back(16);
4543   }
4544   if (ST->is64Bit()) {
4545     Options.LoadSizes.push_back(8);
4546   }
4547   Options.LoadSizes.push_back(4);
4548   Options.LoadSizes.push_back(2);
4549   Options.LoadSizes.push_back(1);
4550   return Options;
4551 }
4552 
4553 bool X86TTIImpl::enableInterleavedAccessVectorization() {
4554   // TODO: We expect this to be beneficial regardless of arch,
4555   // but there are currently some unexplained performance artifacts on Atom.
4556   // As a temporary solution, disable on Atom.
4557   return !(ST->isAtom());
4558 }
4559 
4560 // Get estimation for interleaved load/store operations for AVX2.
4561 // \p Factor is the interleaved-access factor (stride) - number of
4562 // (interleaved) elements in the group.
4563 // \p Indices contains the indices for a strided load: when the
4564 // interleaved load has gaps they indicate which elements are used.
4565 // If Indices is empty (or if the number of indices is equal to the size
4566 // of the interleaved-access as given in \p Factor) the access has no gaps.
4567 //
4568 // As opposed to AVX-512, AVX2 does not have generic shuffles that allow
4569 // computing the cost using a generic formula as a function of generic
4570 // shuffles. We therefore use a lookup table instead, filled according to
4571 // the instruction sequences that codegen currently generates.
4572 InstructionCost X86TTIImpl::getInterleavedMemoryOpCostAVX2(
4573     unsigned Opcode, FixedVectorType *VecTy, unsigned Factor,
4574     ArrayRef<unsigned> Indices, Align Alignment, unsigned AddressSpace,
4575     TTI::TargetCostKind CostKind, bool UseMaskForCond, bool UseMaskForGaps) {
4576 
4577   if (UseMaskForCond || UseMaskForGaps)
4578     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
4579                                              Alignment, AddressSpace, CostKind,
4580                                              UseMaskForCond, UseMaskForGaps);
4581 
4582   // We currently Support only fully-interleaved groups, with no gaps.
4583   // TODO: Support also strided loads (interleaved-groups with gaps).
4584   if (Indices.size() && Indices.size() != Factor)
4585     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
4586                                              Alignment, AddressSpace,
4587                                              CostKind);
4588 
4589   // VecTy for interleave memop is <VF*Factor x Elt>.
4590   // So, for VF=4, Interleave Factor = 3, Element type = i32 we have
4591   // VecTy = <12 x i32>.
4592   MVT LegalVT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
4593 
4594   // This function can be called with VecTy=<6xi128>, Factor=3, in which case
4595   // the VF=2, while v2i128 is an unsupported MVT vector type
4596   // (see MachineValueType.h::getVectorVT()).
4597   if (!LegalVT.isVector())
4598     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
4599                                              Alignment, AddressSpace,
4600                                              CostKind);
4601 
4602   unsigned VF = VecTy->getNumElements() / Factor;
4603   Type *ScalarTy = VecTy->getElementType();
4604   // Deduplicate entries, model floats/pointers as appropriately-sized integers.
4605   if (!ScalarTy->isIntegerTy())
4606     ScalarTy =
4607         Type::getIntNTy(ScalarTy->getContext(), DL.getTypeSizeInBits(ScalarTy));
4608 
4609   // Calculate the number of memory operations (NumOfMemOps), required
4610   // for load/store the VecTy.
4611   unsigned VecTySize = DL.getTypeStoreSize(VecTy);
4612   unsigned LegalVTSize = LegalVT.getStoreSize();
4613   unsigned NumOfMemOps = (VecTySize + LegalVTSize - 1) / LegalVTSize;
4614 
4615   // Get the cost of one memory operation.
4616   auto *SingleMemOpTy = FixedVectorType::get(VecTy->getElementType(),
4617                                              LegalVT.getVectorNumElements());
4618   InstructionCost MemOpCost = getMemoryOpCost(
4619       Opcode, SingleMemOpTy, MaybeAlign(Alignment), AddressSpace, CostKind);
4620 
4621   auto *VT = FixedVectorType::get(ScalarTy, VF);
4622   EVT ETy = TLI->getValueType(DL, VT);
4623   if (!ETy.isSimple())
4624     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
4625                                              Alignment, AddressSpace,
4626                                              CostKind);
4627 
4628   // TODO: Complete for other data-types and strides.
4629   // Each combination of Stride, element bit width and VF results in a different
4630   // sequence; The cost tables are therefore accessed with:
4631   // Factor (stride) and VectorType=VFxiN.
4632   // The Cost accounts only for the shuffle sequence;
4633   // The cost of the loads/stores is accounted for separately.
4634   //
4635   static const CostTblEntry AVX2InterleavedLoadTbl[] = {
4636     { 2, MVT::v4i64, 6 }, //(load 8i64 and) deinterleave into 2 x 4i64
4637 
4638     { 3, MVT::v2i8,  10 }, //(load 6i8 and)  deinterleave into 3 x 2i8
4639     { 3, MVT::v4i8,  4 },  //(load 12i8 and) deinterleave into 3 x 4i8
4640     { 3, MVT::v8i8,  9 },  //(load 24i8 and) deinterleave into 3 x 8i8
4641     { 3, MVT::v16i8, 11},  //(load 48i8 and) deinterleave into 3 x 16i8
4642     { 3, MVT::v32i8, 13},  //(load 96i8 and) deinterleave into 3 x 32i8
4643 
4644     { 3, MVT::v8i32, 17 }, //(load 24i32 and)deinterleave into 3 x 8i32
4645 
4646     { 4, MVT::v2i8,  12 }, //(load 8i8 and)   deinterleave into 4 x 2i8
4647     { 4, MVT::v4i8,  4 },  //(load 16i8 and)  deinterleave into 4 x 4i8
4648     { 4, MVT::v8i8,  20 }, //(load 32i8 and)  deinterleave into 4 x 8i8
4649     { 4, MVT::v16i8, 39 }, //(load 64i8 and)  deinterleave into 4 x 16i8
4650     { 4, MVT::v32i8, 80 }, //(load 128i8 and) deinterleave into 4 x 32i8
4651 
4652     { 8, MVT::v8i32, 40 }  //(load 64i32 and)deinterleave into 8 x 8i32
4653   };
4654 
4655   static const CostTblEntry AVX2InterleavedStoreTbl[] = {
4656     { 2, MVT::v4i64, 6 }, //interleave into 2 x 4i64 into 8i64 (and store)
4657 
4658     { 3, MVT::v2i8,  7 },  //interleave 3 x 2i8  into 6i8 (and store)
4659     { 3, MVT::v4i8,  8 },  //interleave 3 x 4i8  into 12i8 (and store)
4660     { 3, MVT::v8i8,  11 }, //interleave 3 x 8i8  into 24i8 (and store)
4661     { 3, MVT::v16i8, 11 }, //interleave 3 x 16i8 into 48i8 (and store)
4662     { 3, MVT::v32i8, 13 }, //interleave 3 x 32i8 into 96i8 (and store)
4663 
4664     { 4, MVT::v2i8,  12 }, //interleave 4 x 2i8  into 8i8 (and store)
4665     { 4, MVT::v4i8,  9 },  //interleave 4 x 4i8  into 16i8 (and store)
4666     { 4, MVT::v8i8,  10 }, //interleave 4 x 8i8  into 32i8 (and store)
4667     { 4, MVT::v16i8, 10 }, //interleave 4 x 16i8 into 64i8 (and store)
4668     { 4, MVT::v32i8, 12 }  //interleave 4 x 32i8 into 128i8 (and store)
4669   };
4670 
4671   if (Opcode == Instruction::Load) {
4672     if (const auto *Entry =
4673             CostTableLookup(AVX2InterleavedLoadTbl, Factor, ETy.getSimpleVT()))
4674       return NumOfMemOps * MemOpCost + Entry->Cost;
4675   } else {
4676     assert(Opcode == Instruction::Store &&
4677            "Expected Store Instruction at this  point");
4678     if (const auto *Entry =
4679             CostTableLookup(AVX2InterleavedStoreTbl, Factor, ETy.getSimpleVT()))
4680       return NumOfMemOps * MemOpCost + Entry->Cost;
4681   }
4682 
4683   return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
4684                                            Alignment, AddressSpace, CostKind);
4685 }
4686 
4687 // Get estimation for interleaved load/store operations and strided load.
4688 // \p Indices contains indices for strided load.
4689 // \p Factor - the factor of interleaving.
4690 // AVX-512 provides 3-src shuffles that significantly reduces the cost.
4691 InstructionCost X86TTIImpl::getInterleavedMemoryOpCostAVX512(
4692     unsigned Opcode, FixedVectorType *VecTy, unsigned Factor,
4693     ArrayRef<unsigned> Indices, Align Alignment, unsigned AddressSpace,
4694     TTI::TargetCostKind CostKind, bool UseMaskForCond, bool UseMaskForGaps) {
4695 
4696   if (UseMaskForCond || UseMaskForGaps)
4697     return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
4698                                              Alignment, AddressSpace, CostKind,
4699                                              UseMaskForCond, UseMaskForGaps);
4700 
4701   // VecTy for interleave memop is <VF*Factor x Elt>.
4702   // So, for VF=4, Interleave Factor = 3, Element type = i32 we have
4703   // VecTy = <12 x i32>.
4704 
4705   // Calculate the number of memory operations (NumOfMemOps), required
4706   // for load/store the VecTy.
4707   MVT LegalVT = getTLI()->getTypeLegalizationCost(DL, VecTy).second;
4708   unsigned VecTySize = DL.getTypeStoreSize(VecTy);
4709   unsigned LegalVTSize = LegalVT.getStoreSize();
4710   unsigned NumOfMemOps = (VecTySize + LegalVTSize - 1) / LegalVTSize;
4711 
4712   // Get the cost of one memory operation.
4713   auto *SingleMemOpTy = FixedVectorType::get(VecTy->getElementType(),
4714                                              LegalVT.getVectorNumElements());
4715   InstructionCost MemOpCost = getMemoryOpCost(
4716       Opcode, SingleMemOpTy, MaybeAlign(Alignment), AddressSpace, CostKind);
4717 
4718   unsigned VF = VecTy->getNumElements() / Factor;
4719   MVT VT = MVT::getVectorVT(MVT::getVT(VecTy->getScalarType()), VF);
4720 
4721   if (Opcode == Instruction::Load) {
4722     // The tables (AVX512InterleavedLoadTbl and AVX512InterleavedStoreTbl)
4723     // contain the cost of the optimized shuffle sequence that the
4724     // X86InterleavedAccess pass will generate.
4725     // The cost of loads and stores are computed separately from the table.
4726 
4727     // X86InterleavedAccess support only the following interleaved-access group.
4728     static const CostTblEntry AVX512InterleavedLoadTbl[] = {
4729         {3, MVT::v16i8, 12}, //(load 48i8 and) deinterleave into 3 x 16i8
4730         {3, MVT::v32i8, 14}, //(load 96i8 and) deinterleave into 3 x 32i8
4731         {3, MVT::v64i8, 22}, //(load 96i8 and) deinterleave into 3 x 32i8
4732     };
4733 
4734     if (const auto *Entry =
4735             CostTableLookup(AVX512InterleavedLoadTbl, Factor, VT))
4736       return NumOfMemOps * MemOpCost + Entry->Cost;
4737     //If an entry does not exist, fallback to the default implementation.
4738 
4739     // Kind of shuffle depends on number of loaded values.
4740     // If we load the entire data in one register, we can use a 1-src shuffle.
4741     // Otherwise, we'll merge 2 sources in each operation.
4742     TTI::ShuffleKind ShuffleKind =
4743         (NumOfMemOps > 1) ? TTI::SK_PermuteTwoSrc : TTI::SK_PermuteSingleSrc;
4744 
4745     InstructionCost ShuffleCost =
4746         getShuffleCost(ShuffleKind, SingleMemOpTy, None, 0, nullptr);
4747 
4748     unsigned NumOfLoadsInInterleaveGrp =
4749         Indices.size() ? Indices.size() : Factor;
4750     auto *ResultTy = FixedVectorType::get(VecTy->getElementType(),
4751                                           VecTy->getNumElements() / Factor);
4752     InstructionCost NumOfResults =
4753         getTLI()->getTypeLegalizationCost(DL, ResultTy).first *
4754         NumOfLoadsInInterleaveGrp;
4755 
4756     // About a half of the loads may be folded in shuffles when we have only
4757     // one result. If we have more than one result, we do not fold loads at all.
4758     unsigned NumOfUnfoldedLoads =
4759         NumOfResults > 1 ? NumOfMemOps : NumOfMemOps / 2;
4760 
4761     // Get a number of shuffle operations per result.
4762     unsigned NumOfShufflesPerResult =
4763         std::max((unsigned)1, (unsigned)(NumOfMemOps - 1));
4764 
4765     // The SK_MergeTwoSrc shuffle clobbers one of src operands.
4766     // When we have more than one destination, we need additional instructions
4767     // to keep sources.
4768     InstructionCost NumOfMoves = 0;
4769     if (NumOfResults > 1 && ShuffleKind == TTI::SK_PermuteTwoSrc)
4770       NumOfMoves = NumOfResults * NumOfShufflesPerResult / 2;
4771 
4772     InstructionCost Cost = NumOfResults * NumOfShufflesPerResult * ShuffleCost +
4773                            NumOfUnfoldedLoads * MemOpCost + NumOfMoves;
4774 
4775     return Cost;
4776   }
4777 
4778   // Store.
4779   assert(Opcode == Instruction::Store &&
4780          "Expected Store Instruction at this  point");
4781   // X86InterleavedAccess support only the following interleaved-access group.
4782   static const CostTblEntry AVX512InterleavedStoreTbl[] = {
4783       {3, MVT::v16i8, 12}, // interleave 3 x 16i8 into 48i8 (and store)
4784       {3, MVT::v32i8, 14}, // interleave 3 x 32i8 into 96i8 (and store)
4785       {3, MVT::v64i8, 26}, // interleave 3 x 64i8 into 96i8 (and store)
4786 
4787       {4, MVT::v8i8, 10},  // interleave 4 x 8i8  into 32i8  (and store)
4788       {4, MVT::v16i8, 11}, // interleave 4 x 16i8 into 64i8  (and store)
4789       {4, MVT::v32i8, 14}, // interleave 4 x 32i8 into 128i8 (and store)
4790       {4, MVT::v64i8, 24}  // interleave 4 x 32i8 into 256i8 (and store)
4791   };
4792 
4793   if (const auto *Entry =
4794           CostTableLookup(AVX512InterleavedStoreTbl, Factor, VT))
4795     return NumOfMemOps * MemOpCost + Entry->Cost;
4796   //If an entry does not exist, fallback to the default implementation.
4797 
4798   // There is no strided stores meanwhile. And store can't be folded in
4799   // shuffle.
4800   unsigned NumOfSources = Factor; // The number of values to be merged.
4801   InstructionCost ShuffleCost =
4802       getShuffleCost(TTI::SK_PermuteTwoSrc, SingleMemOpTy, None, 0, nullptr);
4803   unsigned NumOfShufflesPerStore = NumOfSources - 1;
4804 
4805   // The SK_MergeTwoSrc shuffle clobbers one of src operands.
4806   // We need additional instructions to keep sources.
4807   unsigned NumOfMoves = NumOfMemOps * NumOfShufflesPerStore / 2;
4808   InstructionCost Cost =
4809       NumOfMemOps * (MemOpCost + NumOfShufflesPerStore * ShuffleCost) +
4810       NumOfMoves;
4811   return Cost;
4812 }
4813 
4814 InstructionCost X86TTIImpl::getInterleavedMemoryOpCost(
4815     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
4816     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
4817     bool UseMaskForCond, bool UseMaskForGaps) {
4818   auto isSupportedOnAVX512 = [](Type *VecTy, bool HasBW) {
4819     Type *EltTy = cast<VectorType>(VecTy)->getElementType();
4820     if (EltTy->isFloatTy() || EltTy->isDoubleTy() || EltTy->isIntegerTy(64) ||
4821         EltTy->isIntegerTy(32) || EltTy->isPointerTy())
4822       return true;
4823     if (EltTy->isIntegerTy(16) || EltTy->isIntegerTy(8))
4824       return HasBW;
4825     return false;
4826   };
4827   if (ST->hasAVX512() && isSupportedOnAVX512(VecTy, ST->hasBWI()))
4828     return getInterleavedMemoryOpCostAVX512(
4829         Opcode, cast<FixedVectorType>(VecTy), Factor, Indices, Alignment,
4830         AddressSpace, CostKind, UseMaskForCond, UseMaskForGaps);
4831   if (ST->hasAVX2())
4832     return getInterleavedMemoryOpCostAVX2(
4833         Opcode, cast<FixedVectorType>(VecTy), Factor, Indices, Alignment,
4834         AddressSpace, CostKind, UseMaskForCond, UseMaskForGaps);
4835 
4836   return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
4837                                            Alignment, AddressSpace, CostKind,
4838                                            UseMaskForCond, UseMaskForGaps);
4839 }
4840