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