1 //===-- X86TargetTransformInfo.cpp - X86 specific TTI pass ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// This file implements a TargetTransformInfo analysis pass specific to the
11 /// X86 target machine. It uses the target's detailed information to provide
12 /// more precise answers to certain TTI queries, while letting the target
13 /// independent and default TTI implementations handle the rest.
14 ///
15 //===----------------------------------------------------------------------===//
16 
17 #include "X86TargetTransformInfo.h"
18 #include "llvm/Analysis/TargetTransformInfo.h"
19 #include "llvm/CodeGen/BasicTTIImpl.h"
20 #include "llvm/IR/IntrinsicInst.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Target/CostTable.h"
23 #include "llvm/Target/TargetLowering.h"
24 
25 using namespace llvm;
26 
27 #define DEBUG_TYPE "x86tti"
28 
29 //===----------------------------------------------------------------------===//
30 //
31 // X86 cost model.
32 //
33 //===----------------------------------------------------------------------===//
34 
35 TargetTransformInfo::PopcntSupportKind
36 X86TTIImpl::getPopcntSupport(unsigned TyWidth) {
37   assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
38   // TODO: Currently the __builtin_popcount() implementation using SSE3
39   //   instructions is inefficient. Once the problem is fixed, we should
40   //   call ST->hasSSE3() instead of ST->hasPOPCNT().
41   return ST->hasPOPCNT() ? TTI::PSK_FastHardware : TTI::PSK_Software;
42 }
43 
44 unsigned X86TTIImpl::getNumberOfRegisters(bool Vector) {
45   if (Vector && !ST->hasSSE1())
46     return 0;
47 
48   if (ST->is64Bit()) {
49     if (Vector && ST->hasAVX512())
50       return 32;
51     return 16;
52   }
53   return 8;
54 }
55 
56 unsigned X86TTIImpl::getRegisterBitWidth(bool Vector) {
57   if (Vector) {
58     if (ST->hasAVX512()) return 512;
59     if (ST->hasAVX()) return 256;
60     if (ST->hasSSE1()) return 128;
61     return 0;
62   }
63 
64   if (ST->is64Bit())
65     return 64;
66 
67   return 32;
68 }
69 
70 unsigned X86TTIImpl::getMaxInterleaveFactor(unsigned VF) {
71   // If the loop will not be vectorized, don't interleave the loop.
72   // Let regular unroll to unroll the loop, which saves the overflow
73   // check and memory check cost.
74   if (VF == 1)
75     return 1;
76 
77   if (ST->isAtom())
78     return 1;
79 
80   // Sandybridge and Haswell have multiple execution ports and pipelined
81   // vector units.
82   if (ST->hasAVX())
83     return 4;
84 
85   return 2;
86 }
87 
88 int X86TTIImpl::getArithmeticInstrCost(
89     unsigned Opcode, Type *Ty, TTI::OperandValueKind Op1Info,
90     TTI::OperandValueKind Op2Info, TTI::OperandValueProperties Opd1PropInfo,
91     TTI::OperandValueProperties Opd2PropInfo) {
92   // Legalize the type.
93   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
94 
95   int ISD = TLI->InstructionOpcodeToISD(Opcode);
96   assert(ISD && "Invalid opcode");
97 
98   if (ISD == ISD::SDIV &&
99       Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
100       Opd2PropInfo == TargetTransformInfo::OP_PowerOf2) {
101     // On X86, vector signed division by constants power-of-two are
102     // normally expanded to the sequence SRA + SRL + ADD + SRA.
103     // The OperandValue properties many not be same as that of previous
104     // operation;conservatively assume OP_None.
105     int Cost = 2 * getArithmeticInstrCost(Instruction::AShr, Ty, Op1Info,
106                                           Op2Info, TargetTransformInfo::OP_None,
107                                           TargetTransformInfo::OP_None);
108     Cost += getArithmeticInstrCost(Instruction::LShr, Ty, Op1Info, Op2Info,
109                                    TargetTransformInfo::OP_None,
110                                    TargetTransformInfo::OP_None);
111     Cost += getArithmeticInstrCost(Instruction::Add, Ty, Op1Info, Op2Info,
112                                    TargetTransformInfo::OP_None,
113                                    TargetTransformInfo::OP_None);
114 
115     return Cost;
116   }
117 
118   static const CostTblEntry AVX2UniformConstCostTable[] = {
119     { ISD::SRA,  MVT::v4i64,   4 }, // 2 x psrad + shuffle.
120 
121     { ISD::SDIV, MVT::v16i16,  6 }, // vpmulhw sequence
122     { ISD::UDIV, MVT::v16i16,  6 }, // vpmulhuw sequence
123     { ISD::SDIV, MVT::v8i32,  15 }, // vpmuldq sequence
124     { ISD::UDIV, MVT::v8i32,  15 }, // vpmuludq sequence
125   };
126 
127   if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
128       ST->hasAVX2()) {
129     if (const auto *Entry = CostTableLookup(AVX2UniformConstCostTable, ISD,
130                                             LT.second))
131       return LT.first * Entry->Cost;
132   }
133 
134   static const CostTblEntry AVX512CostTable[] = {
135     { ISD::SHL,     MVT::v16i32,    1 },
136     { ISD::SRL,     MVT::v16i32,    1 },
137     { ISD::SRA,     MVT::v16i32,    1 },
138     { ISD::SHL,     MVT::v8i64,    1 },
139     { ISD::SRL,     MVT::v8i64,    1 },
140     { ISD::SRA,     MVT::v8i64,    1 },
141   };
142 
143   if (ST->hasAVX512()) {
144     if (const auto *Entry = CostTableLookup(AVX512CostTable, ISD, LT.second))
145       return LT.first * Entry->Cost;
146   }
147 
148   static const CostTblEntry AVX2CostTable[] = {
149     // Shifts on v4i64/v8i32 on AVX2 is legal even though we declare to
150     // customize them to detect the cases where shift amount is a scalar one.
151     { ISD::SHL,     MVT::v4i32,    1 },
152     { ISD::SRL,     MVT::v4i32,    1 },
153     { ISD::SRA,     MVT::v4i32,    1 },
154     { ISD::SHL,     MVT::v8i32,    1 },
155     { ISD::SRL,     MVT::v8i32,    1 },
156     { ISD::SRA,     MVT::v8i32,    1 },
157     { ISD::SHL,     MVT::v2i64,    1 },
158     { ISD::SRL,     MVT::v2i64,    1 },
159     { ISD::SHL,     MVT::v4i64,    1 },
160     { ISD::SRL,     MVT::v4i64,    1 },
161   };
162 
163   // Look for AVX2 lowering tricks.
164   if (ST->hasAVX2()) {
165     if (ISD == ISD::SHL && LT.second == MVT::v16i16 &&
166         (Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
167          Op2Info == TargetTransformInfo::OK_NonUniformConstantValue))
168       // On AVX2, a packed v16i16 shift left by a constant build_vector
169       // is lowered into a vector multiply (vpmullw).
170       return LT.first;
171 
172     if (const auto *Entry = CostTableLookup(AVX2CostTable, ISD, LT.second))
173       return LT.first * Entry->Cost;
174   }
175 
176   static const CostTblEntry XOPCostTable[] = {
177     // 128bit shifts take 1cy, but right shifts require negation beforehand.
178     { ISD::SHL,     MVT::v16i8,    1 },
179     { ISD::SRL,     MVT::v16i8,    2 },
180     { ISD::SRA,     MVT::v16i8,    2 },
181     { ISD::SHL,     MVT::v8i16,    1 },
182     { ISD::SRL,     MVT::v8i16,    2 },
183     { ISD::SRA,     MVT::v8i16,    2 },
184     { ISD::SHL,     MVT::v4i32,    1 },
185     { ISD::SRL,     MVT::v4i32,    2 },
186     { ISD::SRA,     MVT::v4i32,    2 },
187     { ISD::SHL,     MVT::v2i64,    1 },
188     { ISD::SRL,     MVT::v2i64,    2 },
189     { ISD::SRA,     MVT::v2i64,    2 },
190     // 256bit shifts require splitting if AVX2 didn't catch them above.
191     { ISD::SHL,     MVT::v32i8,    2 },
192     { ISD::SRL,     MVT::v32i8,    4 },
193     { ISD::SRA,     MVT::v32i8,    4 },
194     { ISD::SHL,     MVT::v16i16,   2 },
195     { ISD::SRL,     MVT::v16i16,   4 },
196     { ISD::SRA,     MVT::v16i16,   4 },
197     { ISD::SHL,     MVT::v8i32,    2 },
198     { ISD::SRL,     MVT::v8i32,    4 },
199     { ISD::SRA,     MVT::v8i32,    4 },
200     { ISD::SHL,     MVT::v4i64,    2 },
201     { ISD::SRL,     MVT::v4i64,    4 },
202     { ISD::SRA,     MVT::v4i64,    4 },
203   };
204 
205   // Look for XOP lowering tricks.
206   if (ST->hasXOP()) {
207     if (const auto *Entry = CostTableLookup(XOPCostTable, ISD, LT.second))
208       return LT.first * Entry->Cost;
209   }
210 
211   static const CostTblEntry AVX2CustomCostTable[] = {
212     { ISD::SHL,  MVT::v32i8,      11 }, // vpblendvb sequence.
213     { ISD::SHL,  MVT::v16i16,     10 }, // extend/vpsrlvd/pack sequence.
214 
215     { ISD::SRL,  MVT::v32i8,      11 }, // vpblendvb sequence.
216     { ISD::SRL,  MVT::v16i16,     10 }, // extend/vpsrlvd/pack sequence.
217 
218     { ISD::SRA,  MVT::v32i8,      24 }, // vpblendvb sequence.
219     { ISD::SRA,  MVT::v16i16,     10 }, // extend/vpsravd/pack sequence.
220     { ISD::SRA,  MVT::v2i64,       4 }, // srl/xor/sub sequence.
221     { ISD::SRA,  MVT::v4i64,       4 }, // srl/xor/sub sequence.
222 
223     // Vectorizing division is a bad idea. See the SSE2 table for more comments.
224     { ISD::SDIV,  MVT::v32i8,  32*20 },
225     { ISD::SDIV,  MVT::v16i16, 16*20 },
226     { ISD::SDIV,  MVT::v8i32,  8*20 },
227     { ISD::SDIV,  MVT::v4i64,  4*20 },
228     { ISD::UDIV,  MVT::v32i8,  32*20 },
229     { ISD::UDIV,  MVT::v16i16, 16*20 },
230     { ISD::UDIV,  MVT::v8i32,  8*20 },
231     { ISD::UDIV,  MVT::v4i64,  4*20 },
232   };
233 
234   // Look for AVX2 lowering tricks for custom cases.
235   if (ST->hasAVX2()) {
236     if (const auto *Entry = CostTableLookup(AVX2CustomCostTable, ISD,
237                                             LT.second))
238       return LT.first * Entry->Cost;
239   }
240 
241   static const CostTblEntry
242   SSE2UniformConstCostTable[] = {
243     // We don't correctly identify costs of casts because they are marked as
244     // custom.
245     // Constant splats are cheaper for the following instructions.
246     { ISD::SHL,  MVT::v16i8,  1 }, // psllw.
247     { ISD::SHL,  MVT::v32i8,  2 }, // psllw.
248     { ISD::SHL,  MVT::v8i16,  1 }, // psllw.
249     { ISD::SHL,  MVT::v16i16, 2 }, // psllw.
250     { ISD::SHL,  MVT::v4i32,  1 }, // pslld
251     { ISD::SHL,  MVT::v8i32,  2 }, // pslld
252     { ISD::SHL,  MVT::v2i64,  1 }, // psllq.
253     { ISD::SHL,  MVT::v4i64,  2 }, // psllq.
254 
255     { ISD::SRL,  MVT::v16i8,  1 }, // psrlw.
256     { ISD::SRL,  MVT::v32i8,  2 }, // psrlw.
257     { ISD::SRL,  MVT::v8i16,  1 }, // psrlw.
258     { ISD::SRL,  MVT::v16i16, 2 }, // psrlw.
259     { ISD::SRL,  MVT::v4i32,  1 }, // psrld.
260     { ISD::SRL,  MVT::v8i32,  2 }, // psrld.
261     { ISD::SRL,  MVT::v2i64,  1 }, // psrlq.
262     { ISD::SRL,  MVT::v4i64,  2 }, // psrlq.
263 
264     { ISD::SRA,  MVT::v16i8,  4 }, // psrlw, pand, pxor, psubb.
265     { ISD::SRA,  MVT::v32i8,  8 }, // psrlw, pand, pxor, psubb.
266     { ISD::SRA,  MVT::v8i16,  1 }, // psraw.
267     { ISD::SRA,  MVT::v16i16, 2 }, // psraw.
268     { ISD::SRA,  MVT::v4i32,  1 }, // psrad.
269     { ISD::SRA,  MVT::v8i32,  2 }, // psrad.
270     { ISD::SRA,  MVT::v2i64,  4 }, // 2 x psrad + shuffle.
271     { ISD::SRA,  MVT::v4i64,  8 }, // 2 x psrad + shuffle.
272 
273     { ISD::SDIV, MVT::v8i16,  6 }, // pmulhw sequence
274     { ISD::UDIV, MVT::v8i16,  6 }, // pmulhuw sequence
275     { ISD::SDIV, MVT::v4i32, 19 }, // pmuludq sequence
276     { ISD::UDIV, MVT::v4i32, 15 }, // pmuludq sequence
277   };
278 
279   if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
280       ST->hasSSE2()) {
281     // pmuldq sequence.
282     if (ISD == ISD::SDIV && LT.second == MVT::v4i32 && ST->hasSSE41())
283       return LT.first * 15;
284 
285     if (const auto *Entry = CostTableLookup(SSE2UniformConstCostTable, ISD,
286                                             LT.second))
287       return LT.first * Entry->Cost;
288   }
289 
290   if (ISD == ISD::SHL &&
291       Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) {
292     MVT VT = LT.second;
293     // Vector shift left by non uniform constant can be lowered
294     // into vector multiply (pmullw/pmulld).
295     if ((VT == MVT::v8i16 && ST->hasSSE2()) ||
296         (VT == MVT::v4i32 && ST->hasSSE41()))
297       return LT.first;
298 
299     // v16i16 and v8i32 shifts by non-uniform constants are lowered into a
300     // sequence of extract + two vector multiply + insert.
301     if ((VT == MVT::v8i32 || VT == MVT::v16i16) &&
302        (ST->hasAVX() && !ST->hasAVX2()))
303       ISD = ISD::MUL;
304 
305     // A vector shift left by non uniform constant is converted
306     // into a vector multiply; the new multiply is eventually
307     // lowered into a sequence of shuffles and 2 x pmuludq.
308     if (VT == MVT::v4i32 && ST->hasSSE2())
309       ISD = ISD::MUL;
310   }
311 
312   static const CostTblEntry SSE2CostTable[] = {
313     // We don't correctly identify costs of casts because they are marked as
314     // custom.
315     // For some cases, where the shift amount is a scalar we would be able
316     // to generate better code. Unfortunately, when this is the case the value
317     // (the splat) will get hoisted out of the loop, thereby making it invisible
318     // to ISel. The cost model must return worst case assumptions because it is
319     // used for vectorization and we don't want to make vectorized code worse
320     // than scalar code.
321     { ISD::SHL,  MVT::v16i8,    26 }, // cmpgtb sequence.
322     { ISD::SHL,  MVT::v32i8,  2*26 }, // cmpgtb sequence.
323     { ISD::SHL,  MVT::v8i16,    32 }, // cmpgtb sequence.
324     { ISD::SHL,  MVT::v16i16, 2*32 }, // cmpgtb sequence.
325     { ISD::SHL,  MVT::v4i32,   2*5 }, // We optimized this using mul.
326     { ISD::SHL,  MVT::v8i32, 2*2*5 }, // We optimized this using mul.
327     { ISD::SHL,  MVT::v2i64,     4 }, // splat+shuffle sequence.
328     { ISD::SHL,  MVT::v4i64,   2*4 }, // splat+shuffle sequence.
329 
330     { ISD::SRL,  MVT::v16i8,    26 }, // cmpgtb sequence.
331     { ISD::SRL,  MVT::v32i8,  2*26 }, // cmpgtb sequence.
332     { ISD::SRL,  MVT::v8i16,    32 }, // cmpgtb sequence.
333     { ISD::SRL,  MVT::v16i16, 2*32 }, // cmpgtb sequence.
334     { ISD::SRL,  MVT::v4i32,    16 }, // Shift each lane + blend.
335     { ISD::SRL,  MVT::v8i32,  2*16 }, // Shift each lane + blend.
336     { ISD::SRL,  MVT::v2i64,     4 }, // splat+shuffle sequence.
337     { ISD::SRL,  MVT::v4i64,   2*4 }, // splat+shuffle sequence.
338 
339     { ISD::SRA,  MVT::v16i8,    54 }, // unpacked cmpgtb sequence.
340     { ISD::SRA,  MVT::v32i8,  2*54 }, // unpacked cmpgtb sequence.
341     { ISD::SRA,  MVT::v8i16,    32 }, // cmpgtb sequence.
342     { ISD::SRA,  MVT::v16i16, 2*32 }, // cmpgtb sequence.
343     { ISD::SRA,  MVT::v4i32,    16 }, // Shift each lane + blend.
344     { ISD::SRA,  MVT::v8i32,  2*16 }, // Shift each lane + blend.
345     { ISD::SRA,  MVT::v2i64,    12 }, // srl/xor/sub sequence.
346     { ISD::SRA,  MVT::v4i64,  2*12 }, // srl/xor/sub sequence.
347 
348     // It is not a good idea to vectorize division. We have to scalarize it and
349     // in the process we will often end up having to spilling regular
350     // registers. The overhead of division is going to dominate most kernels
351     // anyways so try hard to prevent vectorization of division - it is
352     // generally a bad idea. Assume somewhat arbitrarily that we have to be able
353     // to hide "20 cycles" for each lane.
354     { ISD::SDIV,  MVT::v16i8,  16*20 },
355     { ISD::SDIV,  MVT::v8i16,  8*20 },
356     { ISD::SDIV,  MVT::v4i32,  4*20 },
357     { ISD::SDIV,  MVT::v2i64,  2*20 },
358     { ISD::UDIV,  MVT::v16i8,  16*20 },
359     { ISD::UDIV,  MVT::v8i16,  8*20 },
360     { ISD::UDIV,  MVT::v4i32,  4*20 },
361     { ISD::UDIV,  MVT::v2i64,  2*20 },
362   };
363 
364   if (ST->hasSSE2()) {
365     if (const auto *Entry = CostTableLookup(SSE2CostTable, ISD, LT.second))
366       return LT.first * Entry->Cost;
367   }
368 
369   static const CostTblEntry AVX1CostTable[] = {
370     // We don't have to scalarize unsupported ops. We can issue two half-sized
371     // operations and we only need to extract the upper YMM half.
372     // Two ops + 1 extract + 1 insert = 4.
373     { ISD::MUL,     MVT::v16i16,   4 },
374     { ISD::MUL,     MVT::v8i32,    4 },
375     { ISD::SUB,     MVT::v8i32,    4 },
376     { ISD::ADD,     MVT::v8i32,    4 },
377     { ISD::SUB,     MVT::v4i64,    4 },
378     { ISD::ADD,     MVT::v4i64,    4 },
379     // A v4i64 multiply is custom lowered as two split v2i64 vectors that then
380     // are lowered as a series of long multiplies(3), shifts(4) and adds(2)
381     // Because we believe v4i64 to be a legal type, we must also include the
382     // split factor of two in the cost table. Therefore, the cost here is 18
383     // instead of 9.
384     { ISD::MUL,     MVT::v4i64,    18 },
385   };
386 
387   // Look for AVX1 lowering tricks.
388   if (ST->hasAVX() && !ST->hasAVX2()) {
389     MVT VT = LT.second;
390 
391     if (const auto *Entry = CostTableLookup(AVX1CostTable, ISD, VT))
392       return LT.first * Entry->Cost;
393   }
394 
395   // Custom lowering of vectors.
396   static const CostTblEntry CustomLowered[] = {
397     // A v2i64/v4i64 and multiply is custom lowered as a series of long
398     // multiplies(3), shifts(4) and adds(2).
399     { ISD::MUL,     MVT::v2i64,    9 },
400     { ISD::MUL,     MVT::v4i64,    9 },
401   };
402   if (const auto *Entry = CostTableLookup(CustomLowered, ISD, LT.second))
403     return LT.first * Entry->Cost;
404 
405   // Special lowering of v4i32 mul on sse2, sse3: Lower v4i32 mul as 2x shuffle,
406   // 2x pmuludq, 2x shuffle.
407   if (ISD == ISD::MUL && LT.second == MVT::v4i32 && ST->hasSSE2() &&
408       !ST->hasSSE41())
409     return LT.first * 6;
410 
411   // Fallback to the default implementation.
412   return BaseT::getArithmeticInstrCost(Opcode, Ty, Op1Info, Op2Info);
413 }
414 
415 int X86TTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
416                                Type *SubTp) {
417   // We only estimate the cost of reverse and alternate shuffles.
418   if (Kind != TTI::SK_Reverse && Kind != TTI::SK_Alternate)
419     return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
420 
421   if (Kind == TTI::SK_Reverse) {
422     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
423     int Cost = 1;
424     if (LT.second.getSizeInBits() > 128)
425       Cost = 3; // Extract + insert + copy.
426 
427     // Multiple by the number of parts.
428     return Cost * LT.first;
429   }
430 
431   if (Kind == TTI::SK_Alternate) {
432     // 64-bit packed float vectors (v2f32) are widened to type v4f32.
433     // 64-bit packed integer vectors (v2i32) are promoted to type v2i64.
434     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
435 
436     // The backend knows how to generate a single VEX.256 version of
437     // instruction VPBLENDW if the target supports AVX2.
438     if (ST->hasAVX2() && LT.second == MVT::v16i16)
439       return LT.first;
440 
441     static const CostTblEntry AVXAltShuffleTbl[] = {
442       {ISD::VECTOR_SHUFFLE, MVT::v4i64, 1},  // vblendpd
443       {ISD::VECTOR_SHUFFLE, MVT::v4f64, 1},  // vblendpd
444 
445       {ISD::VECTOR_SHUFFLE, MVT::v8i32, 1},  // vblendps
446       {ISD::VECTOR_SHUFFLE, MVT::v8f32, 1},  // vblendps
447 
448       // This shuffle is custom lowered into a sequence of:
449       //  2x  vextractf128 , 2x vpblendw , 1x vinsertf128
450       {ISD::VECTOR_SHUFFLE, MVT::v16i16, 5},
451 
452       // This shuffle is custom lowered into a long sequence of:
453       //  2x vextractf128 , 4x vpshufb , 2x vpor ,  1x vinsertf128
454       {ISD::VECTOR_SHUFFLE, MVT::v32i8, 9}
455     };
456 
457     if (ST->hasAVX())
458       if (const auto *Entry = CostTableLookup(AVXAltShuffleTbl,
459                                               ISD::VECTOR_SHUFFLE, LT.second))
460         return LT.first * Entry->Cost;
461 
462     static const CostTblEntry SSE41AltShuffleTbl[] = {
463       // These are lowered into movsd.
464       {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
465       {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
466 
467       // packed float vectors with four elements are lowered into BLENDI dag
468       // nodes. A v4i32/v4f32 BLENDI generates a single 'blendps'/'blendpd'.
469       {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
470       {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
471 
472       // This shuffle generates a single pshufw.
473       {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
474 
475       // There is no instruction that matches a v16i8 alternate shuffle.
476       // The backend will expand it into the sequence 'pshufb + pshufb + or'.
477       {ISD::VECTOR_SHUFFLE, MVT::v16i8, 3}
478     };
479 
480     if (ST->hasSSE41())
481       if (const auto *Entry = CostTableLookup(SSE41AltShuffleTbl, ISD::VECTOR_SHUFFLE,
482                                               LT.second))
483         return LT.first * Entry->Cost;
484 
485     static const CostTblEntry SSSE3AltShuffleTbl[] = {
486       {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},  // movsd
487       {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},  // movsd
488 
489       // SSE3 doesn't have 'blendps'. The following shuffles are expanded into
490       // the sequence 'shufps + pshufd'
491       {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
492       {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
493 
494       {ISD::VECTOR_SHUFFLE, MVT::v8i16, 3}, // pshufb + pshufb + or
495       {ISD::VECTOR_SHUFFLE, MVT::v16i8, 3}  // pshufb + pshufb + or
496     };
497 
498     if (ST->hasSSSE3())
499       if (const auto *Entry = CostTableLookup(SSSE3AltShuffleTbl,
500                                               ISD::VECTOR_SHUFFLE, LT.second))
501         return LT.first * Entry->Cost;
502 
503     static const CostTblEntry SSEAltShuffleTbl[] = {
504       {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},  // movsd
505       {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},  // movsd
506 
507       {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2}, // shufps + pshufd
508       {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2}, // shufps + pshufd
509 
510       // This is expanded into a long sequence of four extract + four insert.
511       {ISD::VECTOR_SHUFFLE, MVT::v8i16, 8}, // 4 x pextrw + 4 pinsrw.
512 
513       // 8 x (pinsrw + pextrw + and + movb + movzb + or)
514       {ISD::VECTOR_SHUFFLE, MVT::v16i8, 48}
515     };
516 
517     // Fall-back (SSE3 and SSE2).
518     if (const auto *Entry = CostTableLookup(SSEAltShuffleTbl,
519                                             ISD::VECTOR_SHUFFLE, LT.second))
520       return LT.first * Entry->Cost;
521     return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
522   }
523 
524   return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
525 }
526 
527 int X86TTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) {
528   int ISD = TLI->InstructionOpcodeToISD(Opcode);
529   assert(ISD && "Invalid opcode");
530 
531   // FIXME: Need a better design of the cost table to handle non-simple types of
532   // potential massive combinations (elem_num x src_type x dst_type).
533 
534   static const TypeConversionCostTblEntry AVX512DQConversionTbl[] = {
535     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i64,  1 },
536     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i64,  1 },
537     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i64,  1 },
538     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i64,  1 },
539     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i64,  1 },
540     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i64,  1 },
541 
542     { ISD::FP_TO_UINT,  MVT::v2i64, MVT::v2f64, 1 },
543     { ISD::FP_TO_UINT,  MVT::v4i64, MVT::v4f64, 1 },
544     { ISD::FP_TO_UINT,  MVT::v8i64, MVT::v8f64, 1 },
545     { ISD::FP_TO_UINT,  MVT::v2i64, MVT::v2f32, 1 },
546     { ISD::FP_TO_UINT,  MVT::v4i64, MVT::v4f32, 1 },
547     { ISD::FP_TO_UINT,  MVT::v8i64, MVT::v8f32, 1 },
548   };
549 
550   static const TypeConversionCostTblEntry AVX512FConversionTbl[] = {
551     { ISD::FP_EXTEND, MVT::v8f64,   MVT::v8f32,  1 },
552     { ISD::FP_EXTEND, MVT::v8f64,   MVT::v16f32, 3 },
553     { ISD::FP_ROUND,  MVT::v8f32,   MVT::v8f64,  1 },
554 
555     { ISD::TRUNCATE,  MVT::v16i8,   MVT::v16i32, 1 },
556     { ISD::TRUNCATE,  MVT::v16i16,  MVT::v16i32, 1 },
557     { ISD::TRUNCATE,  MVT::v8i16,   MVT::v8i64,  1 },
558     { ISD::TRUNCATE,  MVT::v8i32,   MVT::v8i64,  1 },
559 
560     // v16i1 -> v16i32 - load + broadcast
561     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i1,  2 },
562     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i1,  2 },
563 
564     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8,  1 },
565     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8,  1 },
566     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i16, 1 },
567     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i16, 1 },
568     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i32,  1 },
569     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i32,  1 },
570     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i16,  1 },
571     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i16,  1 },
572 
573     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i1,  3 },
574     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i8,  2 },
575     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i16, 2 },
576     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i32, 1 },
577     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i1,   4 },
578     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i8,   2 },
579     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i16,  2 },
580     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i32,  1 },
581 
582     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i1,  3 },
583     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i8,  2 },
584     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i16, 2 },
585     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i32, 1 },
586     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i32,  1 },
587     { ISD::UINT_TO_FP,  MVT::v4f32,  MVT::v4i32,  1 },
588     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i1,   4 },
589     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i16,  2 },
590     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i32,  1 },
591     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i8,   2 },
592     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i8,   2 },
593     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i16,  2 },
594     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i8,   2 },
595     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i16,  2 },
596     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i32,  1 },
597     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i8,   2 },
598     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i16,  5 },
599     { ISD::UINT_TO_FP,  MVT::v2f32,  MVT::v2i32,  2 },
600     { ISD::UINT_TO_FP,  MVT::v2f64,  MVT::v2i64,  5 },
601     { ISD::UINT_TO_FP,  MVT::v4f64,  MVT::v4i64, 12 },
602     { ISD::UINT_TO_FP,  MVT::v8f64,  MVT::v8i64, 26 },
603 
604     { ISD::FP_TO_UINT,  MVT::v2i32,  MVT::v2f32,  1 },
605     { ISD::FP_TO_UINT,  MVT::v4i32,  MVT::v4f32,  1 },
606     { ISD::FP_TO_UINT,  MVT::v8i32,  MVT::v8f32,  1 },
607     { ISD::FP_TO_UINT,  MVT::v16i32, MVT::v16f32, 1 },
608   };
609 
610   static const TypeConversionCostTblEntry AVX2ConversionTbl[] = {
611     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8,  1 },
612     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8,  1 },
613     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i1,   3 },
614     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i1,   3 },
615     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i8,   3 },
616     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i8,   3 },
617     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16,  1 },
618     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16,  1 },
619     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i1,   3 },
620     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i1,   3 },
621     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i8,   3 },
622     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i8,   3 },
623     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i16,  3 },
624     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i16,  3 },
625     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i32,  1 },
626     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i32,  1 },
627 
628     { ISD::TRUNCATE,    MVT::v4i8,   MVT::v4i64,  2 },
629     { ISD::TRUNCATE,    MVT::v4i16,  MVT::v4i64,  2 },
630     { ISD::TRUNCATE,    MVT::v4i32,  MVT::v4i64,  2 },
631     { ISD::TRUNCATE,    MVT::v8i8,   MVT::v8i32,  2 },
632     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v8i32,  2 },
633     { ISD::TRUNCATE,    MVT::v8i32,  MVT::v8i64,  4 },
634 
635     { ISD::FP_EXTEND,   MVT::v8f64,  MVT::v8f32,  3 },
636     { ISD::FP_ROUND,    MVT::v8f32,  MVT::v8f64,  3 },
637 
638     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i32,  8 },
639   };
640 
641   static const TypeConversionCostTblEntry AVXConversionTbl[] = {
642     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 4 },
643     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 4 },
644     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i1,  7 },
645     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i1,  4 },
646     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i8,  7 },
647     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i8,  4 },
648     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16, 4 },
649     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16, 4 },
650     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i1,  6 },
651     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i1,  4 },
652     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i8,  6 },
653     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i8,  4 },
654     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i16, 6 },
655     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i16, 3 },
656     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i32, 4 },
657     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i32, 4 },
658 
659     { ISD::TRUNCATE,    MVT::v4i8,  MVT::v4i64,  4 },
660     { ISD::TRUNCATE,    MVT::v4i16, MVT::v4i64,  4 },
661     { ISD::TRUNCATE,    MVT::v4i32, MVT::v4i64,  4 },
662     { ISD::TRUNCATE,    MVT::v8i8,  MVT::v8i32,  4 },
663     { ISD::TRUNCATE,    MVT::v8i16, MVT::v8i32,  5 },
664     { ISD::TRUNCATE,    MVT::v16i8, MVT::v16i16, 4 },
665     { ISD::TRUNCATE,    MVT::v8i32, MVT::v8i64,  9 },
666 
667     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i1,  8 },
668     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i8,  8 },
669     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i16, 5 },
670     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i32, 1 },
671     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i1,  3 },
672     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i8,  3 },
673     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i16, 3 },
674     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i32, 1 },
675     { ISD::SINT_TO_FP,  MVT::v4f64, MVT::v4i1,  3 },
676     { ISD::SINT_TO_FP,  MVT::v4f64, MVT::v4i8,  3 },
677     { ISD::SINT_TO_FP,  MVT::v4f64, MVT::v4i16, 3 },
678     { ISD::SINT_TO_FP,  MVT::v4f64, MVT::v4i32, 1 },
679 
680     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i1,  6 },
681     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i8,  5 },
682     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i16, 5 },
683     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i32, 9 },
684     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i1,  7 },
685     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i8,  2 },
686     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i16, 2 },
687     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i32, 6 },
688     { ISD::UINT_TO_FP,  MVT::v4f64, MVT::v4i1,  7 },
689     { ISD::UINT_TO_FP,  MVT::v4f64, MVT::v4i8,  2 },
690     { ISD::UINT_TO_FP,  MVT::v4f64, MVT::v4i16, 2 },
691     { ISD::UINT_TO_FP,  MVT::v4f64, MVT::v4i32, 6 },
692     // The generic code to compute the scalar overhead is currently broken.
693     // Workaround this limitation by estimating the scalarization overhead
694     // here. We have roughly 10 instructions per scalar element.
695     // Multiply that by the vector width.
696     // FIXME: remove that when PR19268 is fixed.
697     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i64, 2*10 },
698     { ISD::UINT_TO_FP,  MVT::v4f64, MVT::v4i64, 4*10 },
699 
700     { ISD::FP_TO_SINT,  MVT::v8i8,  MVT::v8f32, 7 },
701     { ISD::FP_TO_SINT,  MVT::v4i8,  MVT::v4f32, 1 },
702     // This node is expanded into scalarized operations but BasicTTI is overly
703     // optimistic estimating its cost.  It computes 3 per element (one
704     // vector-extract, one scalar conversion and one vector-insert).  The
705     // problem is that the inserts form a read-modify-write chain so latency
706     // should be factored in too.  Inflating the cost per element by 1.
707     { ISD::FP_TO_UINT,  MVT::v8i32, MVT::v8f32, 8*4 },
708     { ISD::FP_TO_UINT,  MVT::v4i32, MVT::v4f64, 4*4 },
709   };
710 
711   static const TypeConversionCostTblEntry SSE41ConversionTbl[] = {
712     { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32,   2 },
713     { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32,   2 },
714     { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16,   2 },
715     { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16,   2 },
716     { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i8,    2 },
717     { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i8,    2 },
718 
719     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i16, 4 },
720     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i16, 4 },
721     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16,  2 },
722     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16,  2 },
723     { ISD::ZERO_EXTEND, MVT::v4i32,  MVT::v4i16,  1 },
724     { ISD::SIGN_EXTEND, MVT::v4i32,  MVT::v4i16,  1 },
725     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8,  4 },
726     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8,  4 },
727     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i8,   2 },
728     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i8,   2 },
729     { ISD::ZERO_EXTEND, MVT::v4i32,  MVT::v4i8,   1 },
730     { ISD::SIGN_EXTEND, MVT::v4i32,  MVT::v4i8,   1 },
731     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8,  2 },
732     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8,  2 },
733     { ISD::ZERO_EXTEND, MVT::v8i16,  MVT::v8i8,   1 },
734     { ISD::SIGN_EXTEND, MVT::v8i16,  MVT::v8i8,   1 },
735     { ISD::ZERO_EXTEND, MVT::v4i16,  MVT::v4i8,   1 },
736     { ISD::SIGN_EXTEND, MVT::v4i16,  MVT::v4i8,   2 },
737 
738     { ISD::TRUNCATE,    MVT::v16i16, MVT::v16i32, 6 },
739     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v8i32,  3 },
740     { ISD::TRUNCATE,    MVT::v4i16,  MVT::v4i32,  1 },
741     { ISD::TRUNCATE,    MVT::v8i8,   MVT::v8i32,  3 },
742     { ISD::TRUNCATE,    MVT::v4i8,   MVT::v4i32,  1 },
743     { ISD::TRUNCATE,    MVT::v8i8,   MVT::v8i16,  1 },
744     { ISD::TRUNCATE,    MVT::v4i8,   MVT::v4i16,  2 },
745   };
746 
747   static const TypeConversionCostTblEntry SSE2ConversionTbl[] = {
748     // These are somewhat magic numbers justified by looking at the output of
749     // Intel's IACA, running some kernels and making sure when we take
750     // legalization into account the throughput will be overestimated.
751     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 2*10 },
752     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v4i32, 4*10 },
753     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v8i16, 8*10 },
754     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v16i8, 16*10 },
755     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i64, 2*10 },
756     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v4i32, 4*10 },
757     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v8i16, 8*10 },
758     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v16i8, 16*10 },
759     // There are faster sequences for float conversions.
760     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v2i64, 15 },
761     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 8 },
762     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v8i16, 15 },
763     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v16i8, 8 },
764     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v2i64, 15 },
765     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 15 },
766     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v8i16, 15 },
767     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v16i8, 8 },
768 
769     { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32,   3 },
770     { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32,   5 },
771     { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16,   3 },
772     { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16,  10 },
773     { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i8,    4 },
774     { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i8,    8 },
775 
776     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i16, 6 },
777     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i16, 8 },
778     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16,  3 },
779     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16,  4 },
780     { ISD::ZERO_EXTEND, MVT::v4i32,  MVT::v4i16,  1 },
781     { ISD::SIGN_EXTEND, MVT::v4i32,  MVT::v4i16,  2 },
782     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8,  9 },
783     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8,  12 },
784     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i8,   6 },
785     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i8,   6 },
786     { ISD::ZERO_EXTEND, MVT::v4i32,  MVT::v4i8,   2 },
787     { ISD::SIGN_EXTEND, MVT::v4i32,  MVT::v4i8,   3 },
788     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8,  3 },
789     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8,  4 },
790     { ISD::ZERO_EXTEND, MVT::v8i16,  MVT::v8i8,   1 },
791     { ISD::SIGN_EXTEND, MVT::v8i16,  MVT::v8i8,   2 },
792     { ISD::ZERO_EXTEND, MVT::v4i16,  MVT::v4i8,   1 },
793     { ISD::SIGN_EXTEND, MVT::v4i16,  MVT::v4i8,   6 },
794 
795     { ISD::TRUNCATE,    MVT::v16i16, MVT::v16i32, 10 },
796     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v8i32,  5 },
797     { ISD::TRUNCATE,    MVT::v4i16,  MVT::v4i32,  3 },
798     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v16i32, 7 },
799     { ISD::TRUNCATE,    MVT::v8i8,   MVT::v8i32,  4 },
800     { ISD::TRUNCATE,    MVT::v4i8,   MVT::v4i32,  3 },
801     { ISD::TRUNCATE,    MVT::v16i8,  MVT::v16i16, 3 },
802     { ISD::TRUNCATE,    MVT::v8i8,   MVT::v8i16,  2 },
803     { ISD::TRUNCATE,    MVT::v4i8,   MVT::v4i16,  4 },
804   };
805 
806   std::pair<int, MVT> LTSrc = TLI->getTypeLegalizationCost(DL, Src);
807   std::pair<int, MVT> LTDest = TLI->getTypeLegalizationCost(DL, Dst);
808 
809   if (ST->hasSSE2() && !ST->hasAVX()) {
810     if (const auto *Entry = ConvertCostTableLookup(SSE2ConversionTbl, ISD,
811                                                    LTDest.second, LTSrc.second))
812       return LTSrc.first * Entry->Cost;
813   }
814 
815   EVT SrcTy = TLI->getValueType(DL, Src);
816   EVT DstTy = TLI->getValueType(DL, Dst);
817 
818   // The function getSimpleVT only handles simple value types.
819   if (!SrcTy.isSimple() || !DstTy.isSimple())
820     return BaseT::getCastInstrCost(Opcode, Dst, Src);
821 
822   if (ST->hasDQI())
823     if (const auto *Entry = ConvertCostTableLookup(AVX512DQConversionTbl, ISD,
824                                                    DstTy.getSimpleVT(),
825                                                    SrcTy.getSimpleVT()))
826       return Entry->Cost;
827 
828   if (ST->hasAVX512())
829     if (const auto *Entry = ConvertCostTableLookup(AVX512FConversionTbl, ISD,
830                                                    DstTy.getSimpleVT(),
831                                                    SrcTy.getSimpleVT()))
832       return Entry->Cost;
833 
834   if (ST->hasAVX2()) {
835     if (const auto *Entry = ConvertCostTableLookup(AVX2ConversionTbl, ISD,
836                                                    DstTy.getSimpleVT(),
837                                                    SrcTy.getSimpleVT()))
838       return Entry->Cost;
839   }
840 
841   if (ST->hasAVX()) {
842     if (const auto *Entry = ConvertCostTableLookup(AVXConversionTbl, ISD,
843                                                    DstTy.getSimpleVT(),
844                                                    SrcTy.getSimpleVT()))
845       return Entry->Cost;
846   }
847 
848   if (ST->hasSSE41()) {
849     if (const auto *Entry = ConvertCostTableLookup(SSE41ConversionTbl, ISD,
850                                                    DstTy.getSimpleVT(),
851                                                    SrcTy.getSimpleVT()))
852       return Entry->Cost;
853   }
854 
855   if (ST->hasSSE2()) {
856     if (const auto *Entry = ConvertCostTableLookup(SSE2ConversionTbl, ISD,
857                                                    DstTy.getSimpleVT(),
858                                                    SrcTy.getSimpleVT()))
859       return Entry->Cost;
860   }
861 
862   return BaseT::getCastInstrCost(Opcode, Dst, Src);
863 }
864 
865 int X86TTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy) {
866   // Legalize the type.
867   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
868 
869   MVT MTy = LT.second;
870 
871   int ISD = TLI->InstructionOpcodeToISD(Opcode);
872   assert(ISD && "Invalid opcode");
873 
874   static const CostTblEntry SSE2CostTbl[] = {
875     { ISD::SETCC,   MVT::v2i64,   8 },
876     { ISD::SETCC,   MVT::v4i32,   1 },
877     { ISD::SETCC,   MVT::v8i16,   1 },
878     { ISD::SETCC,   MVT::v16i8,   1 },
879   };
880 
881   static const CostTblEntry SSE42CostTbl[] = {
882     { ISD::SETCC,   MVT::v2f64,   1 },
883     { ISD::SETCC,   MVT::v4f32,   1 },
884     { ISD::SETCC,   MVT::v2i64,   1 },
885   };
886 
887   static const CostTblEntry AVX1CostTbl[] = {
888     { ISD::SETCC,   MVT::v4f64,   1 },
889     { ISD::SETCC,   MVT::v8f32,   1 },
890     // AVX1 does not support 8-wide integer compare.
891     { ISD::SETCC,   MVT::v4i64,   4 },
892     { ISD::SETCC,   MVT::v8i32,   4 },
893     { ISD::SETCC,   MVT::v16i16,  4 },
894     { ISD::SETCC,   MVT::v32i8,   4 },
895   };
896 
897   static const CostTblEntry AVX2CostTbl[] = {
898     { ISD::SETCC,   MVT::v4i64,   1 },
899     { ISD::SETCC,   MVT::v8i32,   1 },
900     { ISD::SETCC,   MVT::v16i16,  1 },
901     { ISD::SETCC,   MVT::v32i8,   1 },
902   };
903 
904   static const CostTblEntry AVX512CostTbl[] = {
905     { ISD::SETCC,   MVT::v8i64,   1 },
906     { ISD::SETCC,   MVT::v16i32,  1 },
907     { ISD::SETCC,   MVT::v8f64,   1 },
908     { ISD::SETCC,   MVT::v16f32,  1 },
909   };
910 
911   if (ST->hasAVX512())
912     if (const auto *Entry = CostTableLookup(AVX512CostTbl, ISD, MTy))
913       return LT.first * Entry->Cost;
914 
915   if (ST->hasAVX2())
916     if (const auto *Entry = CostTableLookup(AVX2CostTbl, ISD, MTy))
917       return LT.first * Entry->Cost;
918 
919   if (ST->hasAVX())
920     if (const auto *Entry = CostTableLookup(AVX1CostTbl, ISD, MTy))
921       return LT.first * Entry->Cost;
922 
923   if (ST->hasSSE42())
924     if (const auto *Entry = CostTableLookup(SSE42CostTbl, ISD, MTy))
925       return LT.first * Entry->Cost;
926 
927   if (ST->hasSSE2())
928     if (const auto *Entry = CostTableLookup(SSE2CostTbl, ISD, MTy))
929       return LT.first * Entry->Cost;
930 
931   return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy);
932 }
933 
934 int X86TTIImpl::getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
935                                       ArrayRef<Type *> Tys, FastMathFlags FMF) {
936   static const CostTblEntry XOPCostTbl[] = {
937     { ISD::BITREVERSE, MVT::v4i64,   4 },
938     { ISD::BITREVERSE, MVT::v8i32,   4 },
939     { ISD::BITREVERSE, MVT::v16i16,  4 },
940     { ISD::BITREVERSE, MVT::v32i8,   4 },
941     { ISD::BITREVERSE, MVT::v2i64,   1 },
942     { ISD::BITREVERSE, MVT::v4i32,   1 },
943     { ISD::BITREVERSE, MVT::v8i16,   1 },
944     { ISD::BITREVERSE, MVT::v16i8,   1 },
945     { ISD::BITREVERSE, MVT::i64,     3 },
946     { ISD::BITREVERSE, MVT::i32,     3 },
947     { ISD::BITREVERSE, MVT::i16,     3 },
948     { ISD::BITREVERSE, MVT::i8,      3 }
949   };
950   static const CostTblEntry AVX2CostTbl[] = {
951     { ISD::BITREVERSE, MVT::v4i64,   5 },
952     { ISD::BITREVERSE, MVT::v8i32,   5 },
953     { ISD::BITREVERSE, MVT::v16i16,  5 },
954     { ISD::BITREVERSE, MVT::v32i8,   5 }
955   };
956   static const CostTblEntry AVX1CostTbl[] = {
957     { ISD::BITREVERSE, MVT::v4i64,  10 },
958     { ISD::BITREVERSE, MVT::v8i32,  10 },
959     { ISD::BITREVERSE, MVT::v16i16, 10 },
960     { ISD::BITREVERSE, MVT::v32i8,  10 }
961   };
962   static const CostTblEntry SSSE3CostTbl[] = {
963     { ISD::BITREVERSE, MVT::v2i64,   5 },
964     { ISD::BITREVERSE, MVT::v4i32,   5 },
965     { ISD::BITREVERSE, MVT::v8i16,   5 },
966     { ISD::BITREVERSE, MVT::v16i8,   5 }
967   };
968 
969   unsigned ISD = ISD::DELETED_NODE;
970   switch (IID) {
971   default:
972     break;
973   case Intrinsic::bitreverse:
974     ISD = ISD::BITREVERSE;
975     break;
976   }
977 
978   // Legalize the type.
979   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, RetTy);
980   MVT MTy = LT.second;
981 
982   // Attempt to lookup cost.
983   if (ST->hasXOP())
984     if (const auto *Entry = CostTableLookup(XOPCostTbl, ISD, MTy))
985       return LT.first * Entry->Cost;
986 
987   if (ST->hasAVX2())
988     if (const auto *Entry = CostTableLookup(AVX2CostTbl, ISD, MTy))
989       return LT.first * Entry->Cost;
990 
991   if (ST->hasAVX())
992     if (const auto *Entry = CostTableLookup(AVX1CostTbl, ISD, MTy))
993       return LT.first * Entry->Cost;
994 
995   if (ST->hasSSSE3())
996     if (const auto *Entry = CostTableLookup(SSSE3CostTbl, ISD, MTy))
997       return LT.first * Entry->Cost;
998 
999   return BaseT::getIntrinsicInstrCost(IID, RetTy, Tys, FMF);
1000 }
1001 
1002 int X86TTIImpl::getIntrinsicInstrCost(Intrinsic::ID IID, Type *RetTy,
1003                                       ArrayRef<Value *> Args, FastMathFlags FMF) {
1004   return BaseT::getIntrinsicInstrCost(IID, RetTy, Args, FMF);
1005 }
1006 
1007 int X86TTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) {
1008   assert(Val->isVectorTy() && "This must be a vector type");
1009 
1010   Type *ScalarType = Val->getScalarType();
1011 
1012   if (Index != -1U) {
1013     // Legalize the type.
1014     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Val);
1015 
1016     // This type is legalized to a scalar type.
1017     if (!LT.second.isVector())
1018       return 0;
1019 
1020     // The type may be split. Normalize the index to the new type.
1021     unsigned Width = LT.second.getVectorNumElements();
1022     Index = Index % Width;
1023 
1024     // Floating point scalars are already located in index #0.
1025     if (ScalarType->isFloatingPointTy() && Index == 0)
1026       return 0;
1027   }
1028 
1029   // Add to the base cost if we know that the extracted element of a vector is
1030   // destined to be moved to and used in the integer register file.
1031   int RegisterFileMoveCost = 0;
1032   if (Opcode == Instruction::ExtractElement && ScalarType->isPointerTy())
1033     RegisterFileMoveCost = 1;
1034 
1035   return BaseT::getVectorInstrCost(Opcode, Val, Index) + RegisterFileMoveCost;
1036 }
1037 
1038 int X86TTIImpl::getScalarizationOverhead(Type *Ty, bool Insert, bool Extract) {
1039   assert (Ty->isVectorTy() && "Can only scalarize vectors");
1040   int Cost = 0;
1041 
1042   for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
1043     if (Insert)
1044       Cost += getVectorInstrCost(Instruction::InsertElement, Ty, i);
1045     if (Extract)
1046       Cost += getVectorInstrCost(Instruction::ExtractElement, Ty, i);
1047   }
1048 
1049   return Cost;
1050 }
1051 
1052 int X86TTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment,
1053                                 unsigned AddressSpace) {
1054   // Handle non-power-of-two vectors such as <3 x float>
1055   if (VectorType *VTy = dyn_cast<VectorType>(Src)) {
1056     unsigned NumElem = VTy->getVectorNumElements();
1057 
1058     // Handle a few common cases:
1059     // <3 x float>
1060     if (NumElem == 3 && VTy->getScalarSizeInBits() == 32)
1061       // Cost = 64 bit store + extract + 32 bit store.
1062       return 3;
1063 
1064     // <3 x double>
1065     if (NumElem == 3 && VTy->getScalarSizeInBits() == 64)
1066       // Cost = 128 bit store + unpack + 64 bit store.
1067       return 3;
1068 
1069     // Assume that all other non-power-of-two numbers are scalarized.
1070     if (!isPowerOf2_32(NumElem)) {
1071       int Cost = BaseT::getMemoryOpCost(Opcode, VTy->getScalarType(), Alignment,
1072                                         AddressSpace);
1073       int SplitCost = getScalarizationOverhead(Src, Opcode == Instruction::Load,
1074                                                Opcode == Instruction::Store);
1075       return NumElem * Cost + SplitCost;
1076     }
1077   }
1078 
1079   // Legalize the type.
1080   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
1081   assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
1082          "Invalid Opcode");
1083 
1084   // Each load/store unit costs 1.
1085   int Cost = LT.first * 1;
1086 
1087   // This isn't exactly right. We're using slow unaligned 32-byte accesses as a
1088   // proxy for a double-pumped AVX memory interface such as on Sandybridge.
1089   if (LT.second.getStoreSize() == 32 && ST->isUnalignedMem32Slow())
1090     Cost *= 2;
1091 
1092   return Cost;
1093 }
1094 
1095 int X86TTIImpl::getMaskedMemoryOpCost(unsigned Opcode, Type *SrcTy,
1096                                       unsigned Alignment,
1097                                       unsigned AddressSpace) {
1098   VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy);
1099   if (!SrcVTy)
1100     // To calculate scalar take the regular cost, without mask
1101     return getMemoryOpCost(Opcode, SrcTy, Alignment, AddressSpace);
1102 
1103   unsigned NumElem = SrcVTy->getVectorNumElements();
1104   VectorType *MaskTy =
1105     VectorType::get(Type::getInt8Ty(SrcVTy->getContext()), NumElem);
1106   if ((Opcode == Instruction::Load && !isLegalMaskedLoad(SrcVTy)) ||
1107       (Opcode == Instruction::Store && !isLegalMaskedStore(SrcVTy)) ||
1108       !isPowerOf2_32(NumElem)) {
1109     // Scalarization
1110     int MaskSplitCost = getScalarizationOverhead(MaskTy, false, true);
1111     int ScalarCompareCost = getCmpSelInstrCost(
1112         Instruction::ICmp, Type::getInt8Ty(SrcVTy->getContext()), nullptr);
1113     int BranchCost = getCFInstrCost(Instruction::Br);
1114     int MaskCmpCost = NumElem * (BranchCost + ScalarCompareCost);
1115 
1116     int ValueSplitCost = getScalarizationOverhead(
1117         SrcVTy, Opcode == Instruction::Load, Opcode == Instruction::Store);
1118     int MemopCost =
1119         NumElem * BaseT::getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
1120                                          Alignment, AddressSpace);
1121     return MemopCost + ValueSplitCost + MaskSplitCost + MaskCmpCost;
1122   }
1123 
1124   // Legalize the type.
1125   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, SrcVTy);
1126   auto VT = TLI->getValueType(DL, SrcVTy);
1127   int Cost = 0;
1128   if (VT.isSimple() && LT.second != VT.getSimpleVT() &&
1129       LT.second.getVectorNumElements() == NumElem)
1130     // Promotion requires expand/truncate for data and a shuffle for mask.
1131     Cost += getShuffleCost(TTI::SK_Alternate, SrcVTy, 0, nullptr) +
1132             getShuffleCost(TTI::SK_Alternate, MaskTy, 0, nullptr);
1133 
1134   else if (LT.second.getVectorNumElements() > NumElem) {
1135     VectorType *NewMaskTy = VectorType::get(MaskTy->getVectorElementType(),
1136                                             LT.second.getVectorNumElements());
1137     // Expanding requires fill mask with zeroes
1138     Cost += getShuffleCost(TTI::SK_InsertSubvector, NewMaskTy, 0, MaskTy);
1139   }
1140   if (!ST->hasAVX512())
1141     return Cost + LT.first*4; // Each maskmov costs 4
1142 
1143   // AVX-512 masked load/store is cheapper
1144   return Cost+LT.first;
1145 }
1146 
1147 int X86TTIImpl::getAddressComputationCost(Type *Ty, bool IsComplex) {
1148   // Address computations in vectorized code with non-consecutive addresses will
1149   // likely result in more instructions compared to scalar code where the
1150   // computation can more often be merged into the index mode. The resulting
1151   // extra micro-ops can significantly decrease throughput.
1152   unsigned NumVectorInstToHideOverhead = 10;
1153 
1154   if (Ty->isVectorTy() && IsComplex)
1155     return NumVectorInstToHideOverhead;
1156 
1157   return BaseT::getAddressComputationCost(Ty, IsComplex);
1158 }
1159 
1160 int X86TTIImpl::getReductionCost(unsigned Opcode, Type *ValTy,
1161                                  bool IsPairwise) {
1162 
1163   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
1164 
1165   MVT MTy = LT.second;
1166 
1167   int ISD = TLI->InstructionOpcodeToISD(Opcode);
1168   assert(ISD && "Invalid opcode");
1169 
1170   // We use the Intel Architecture Code Analyzer(IACA) to measure the throughput
1171   // and make it as the cost.
1172 
1173   static const CostTblEntry SSE42CostTblPairWise[] = {
1174     { ISD::FADD,  MVT::v2f64,   2 },
1175     { ISD::FADD,  MVT::v4f32,   4 },
1176     { ISD::ADD,   MVT::v2i64,   2 },      // The data reported by the IACA tool is "1.6".
1177     { ISD::ADD,   MVT::v4i32,   3 },      // The data reported by the IACA tool is "3.5".
1178     { ISD::ADD,   MVT::v8i16,   5 },
1179   };
1180 
1181   static const CostTblEntry AVX1CostTblPairWise[] = {
1182     { ISD::FADD,  MVT::v4f32,   4 },
1183     { ISD::FADD,  MVT::v4f64,   5 },
1184     { ISD::FADD,  MVT::v8f32,   7 },
1185     { ISD::ADD,   MVT::v2i64,   1 },      // The data reported by the IACA tool is "1.5".
1186     { ISD::ADD,   MVT::v4i32,   3 },      // The data reported by the IACA tool is "3.5".
1187     { ISD::ADD,   MVT::v4i64,   5 },      // The data reported by the IACA tool is "4.8".
1188     { ISD::ADD,   MVT::v8i16,   5 },
1189     { ISD::ADD,   MVT::v8i32,   5 },
1190   };
1191 
1192   static const CostTblEntry SSE42CostTblNoPairWise[] = {
1193     { ISD::FADD,  MVT::v2f64,   2 },
1194     { ISD::FADD,  MVT::v4f32,   4 },
1195     { ISD::ADD,   MVT::v2i64,   2 },      // The data reported by the IACA tool is "1.6".
1196     { ISD::ADD,   MVT::v4i32,   3 },      // The data reported by the IACA tool is "3.3".
1197     { ISD::ADD,   MVT::v8i16,   4 },      // The data reported by the IACA tool is "4.3".
1198   };
1199 
1200   static const CostTblEntry AVX1CostTblNoPairWise[] = {
1201     { ISD::FADD,  MVT::v4f32,   3 },
1202     { ISD::FADD,  MVT::v4f64,   3 },
1203     { ISD::FADD,  MVT::v8f32,   4 },
1204     { ISD::ADD,   MVT::v2i64,   1 },      // The data reported by the IACA tool is "1.5".
1205     { ISD::ADD,   MVT::v4i32,   3 },      // The data reported by the IACA tool is "2.8".
1206     { ISD::ADD,   MVT::v4i64,   3 },
1207     { ISD::ADD,   MVT::v8i16,   4 },
1208     { ISD::ADD,   MVT::v8i32,   5 },
1209   };
1210 
1211   if (IsPairwise) {
1212     if (ST->hasAVX())
1213       if (const auto *Entry = CostTableLookup(AVX1CostTblPairWise, ISD, MTy))
1214         return LT.first * Entry->Cost;
1215 
1216     if (ST->hasSSE42())
1217       if (const auto *Entry = CostTableLookup(SSE42CostTblPairWise, ISD, MTy))
1218         return LT.first * Entry->Cost;
1219   } else {
1220     if (ST->hasAVX())
1221       if (const auto *Entry = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy))
1222         return LT.first * Entry->Cost;
1223 
1224     if (ST->hasSSE42())
1225       if (const auto *Entry = CostTableLookup(SSE42CostTblNoPairWise, ISD, MTy))
1226         return LT.first * Entry->Cost;
1227   }
1228 
1229   return BaseT::getReductionCost(Opcode, ValTy, IsPairwise);
1230 }
1231 
1232 /// \brief Calculate the cost of materializing a 64-bit value. This helper
1233 /// method might only calculate a fraction of a larger immediate. Therefore it
1234 /// is valid to return a cost of ZERO.
1235 int X86TTIImpl::getIntImmCost(int64_t Val) {
1236   if (Val == 0)
1237     return TTI::TCC_Free;
1238 
1239   if (isInt<32>(Val))
1240     return TTI::TCC_Basic;
1241 
1242   return 2 * TTI::TCC_Basic;
1243 }
1244 
1245 int X86TTIImpl::getIntImmCost(const APInt &Imm, Type *Ty) {
1246   assert(Ty->isIntegerTy());
1247 
1248   unsigned BitSize = Ty->getPrimitiveSizeInBits();
1249   if (BitSize == 0)
1250     return ~0U;
1251 
1252   // Never hoist constants larger than 128bit, because this might lead to
1253   // incorrect code generation or assertions in codegen.
1254   // Fixme: Create a cost model for types larger than i128 once the codegen
1255   // issues have been fixed.
1256   if (BitSize > 128)
1257     return TTI::TCC_Free;
1258 
1259   if (Imm == 0)
1260     return TTI::TCC_Free;
1261 
1262   // Sign-extend all constants to a multiple of 64-bit.
1263   APInt ImmVal = Imm;
1264   if (BitSize & 0x3f)
1265     ImmVal = Imm.sext((BitSize + 63) & ~0x3fU);
1266 
1267   // Split the constant into 64-bit chunks and calculate the cost for each
1268   // chunk.
1269   int Cost = 0;
1270   for (unsigned ShiftVal = 0; ShiftVal < BitSize; ShiftVal += 64) {
1271     APInt Tmp = ImmVal.ashr(ShiftVal).sextOrTrunc(64);
1272     int64_t Val = Tmp.getSExtValue();
1273     Cost += getIntImmCost(Val);
1274   }
1275   // We need at least one instruction to materialize the constant.
1276   return std::max(1, Cost);
1277 }
1278 
1279 int X86TTIImpl::getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm,
1280                               Type *Ty) {
1281   assert(Ty->isIntegerTy());
1282 
1283   unsigned BitSize = Ty->getPrimitiveSizeInBits();
1284   // There is no cost model for constants with a bit size of 0. Return TCC_Free
1285   // here, so that constant hoisting will ignore this constant.
1286   if (BitSize == 0)
1287     return TTI::TCC_Free;
1288 
1289   unsigned ImmIdx = ~0U;
1290   switch (Opcode) {
1291   default:
1292     return TTI::TCC_Free;
1293   case Instruction::GetElementPtr:
1294     // Always hoist the base address of a GetElementPtr. This prevents the
1295     // creation of new constants for every base constant that gets constant
1296     // folded with the offset.
1297     if (Idx == 0)
1298       return 2 * TTI::TCC_Basic;
1299     return TTI::TCC_Free;
1300   case Instruction::Store:
1301     ImmIdx = 0;
1302     break;
1303   case Instruction::ICmp:
1304     // This is an imperfect hack to prevent constant hoisting of
1305     // compares that might be trying to check if a 64-bit value fits in
1306     // 32-bits. The backend can optimize these cases using a right shift by 32.
1307     // Ideally we would check the compare predicate here. There also other
1308     // similar immediates the backend can use shifts for.
1309     if (Idx == 1 && Imm.getBitWidth() == 64) {
1310       uint64_t ImmVal = Imm.getZExtValue();
1311       if (ImmVal == 0x100000000ULL || ImmVal == 0xffffffff)
1312         return TTI::TCC_Free;
1313     }
1314     ImmIdx = 1;
1315     break;
1316   case Instruction::And:
1317     // We support 64-bit ANDs with immediates with 32-bits of leading zeroes
1318     // by using a 32-bit operation with implicit zero extension. Detect such
1319     // immediates here as the normal path expects bit 31 to be sign extended.
1320     if (Idx == 1 && Imm.getBitWidth() == 64 && isUInt<32>(Imm.getZExtValue()))
1321       return TTI::TCC_Free;
1322     // Fallthrough
1323   case Instruction::Add:
1324   case Instruction::Sub:
1325   case Instruction::Mul:
1326   case Instruction::UDiv:
1327   case Instruction::SDiv:
1328   case Instruction::URem:
1329   case Instruction::SRem:
1330   case Instruction::Or:
1331   case Instruction::Xor:
1332     ImmIdx = 1;
1333     break;
1334   // Always return TCC_Free for the shift value of a shift instruction.
1335   case Instruction::Shl:
1336   case Instruction::LShr:
1337   case Instruction::AShr:
1338     if (Idx == 1)
1339       return TTI::TCC_Free;
1340     break;
1341   case Instruction::Trunc:
1342   case Instruction::ZExt:
1343   case Instruction::SExt:
1344   case Instruction::IntToPtr:
1345   case Instruction::PtrToInt:
1346   case Instruction::BitCast:
1347   case Instruction::PHI:
1348   case Instruction::Call:
1349   case Instruction::Select:
1350   case Instruction::Ret:
1351   case Instruction::Load:
1352     break;
1353   }
1354 
1355   if (Idx == ImmIdx) {
1356     int NumConstants = (BitSize + 63) / 64;
1357     int Cost = X86TTIImpl::getIntImmCost(Imm, Ty);
1358     return (Cost <= NumConstants * TTI::TCC_Basic)
1359                ? static_cast<int>(TTI::TCC_Free)
1360                : Cost;
1361   }
1362 
1363   return X86TTIImpl::getIntImmCost(Imm, Ty);
1364 }
1365 
1366 int X86TTIImpl::getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm,
1367                               Type *Ty) {
1368   assert(Ty->isIntegerTy());
1369 
1370   unsigned BitSize = Ty->getPrimitiveSizeInBits();
1371   // There is no cost model for constants with a bit size of 0. Return TCC_Free
1372   // here, so that constant hoisting will ignore this constant.
1373   if (BitSize == 0)
1374     return TTI::TCC_Free;
1375 
1376   switch (IID) {
1377   default:
1378     return TTI::TCC_Free;
1379   case Intrinsic::sadd_with_overflow:
1380   case Intrinsic::uadd_with_overflow:
1381   case Intrinsic::ssub_with_overflow:
1382   case Intrinsic::usub_with_overflow:
1383   case Intrinsic::smul_with_overflow:
1384   case Intrinsic::umul_with_overflow:
1385     if ((Idx == 1) && Imm.getBitWidth() <= 64 && isInt<32>(Imm.getSExtValue()))
1386       return TTI::TCC_Free;
1387     break;
1388   case Intrinsic::experimental_stackmap:
1389     if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
1390       return TTI::TCC_Free;
1391     break;
1392   case Intrinsic::experimental_patchpoint_void:
1393   case Intrinsic::experimental_patchpoint_i64:
1394     if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
1395       return TTI::TCC_Free;
1396     break;
1397   }
1398   return X86TTIImpl::getIntImmCost(Imm, Ty);
1399 }
1400 
1401 // Return an average cost of Gather / Scatter instruction, maybe improved later
1402 int X86TTIImpl::getGSVectorCost(unsigned Opcode, Type *SrcVTy, Value *Ptr,
1403                                 unsigned Alignment, unsigned AddressSpace) {
1404 
1405   assert(isa<VectorType>(SrcVTy) && "Unexpected type in getGSVectorCost");
1406   unsigned VF = SrcVTy->getVectorNumElements();
1407 
1408   // Try to reduce index size from 64 bit (default for GEP)
1409   // to 32. It is essential for VF 16. If the index can't be reduced to 32, the
1410   // operation will use 16 x 64 indices which do not fit in a zmm and needs
1411   // to split. Also check that the base pointer is the same for all lanes,
1412   // and that there's at most one variable index.
1413   auto getIndexSizeInBits = [](Value *Ptr, const DataLayout& DL) {
1414     unsigned IndexSize = DL.getPointerSizeInBits();
1415     GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
1416     if (IndexSize < 64 || !GEP)
1417       return IndexSize;
1418 
1419     unsigned NumOfVarIndices = 0;
1420     Value *Ptrs = GEP->getPointerOperand();
1421     if (Ptrs->getType()->isVectorTy() && !getSplatValue(Ptrs))
1422       return IndexSize;
1423     for (unsigned i = 1; i < GEP->getNumOperands(); ++i) {
1424       if (isa<Constant>(GEP->getOperand(i)))
1425         continue;
1426       Type *IndxTy = GEP->getOperand(i)->getType();
1427       if (IndxTy->isVectorTy())
1428         IndxTy = IndxTy->getVectorElementType();
1429       if ((IndxTy->getPrimitiveSizeInBits() == 64 &&
1430           !isa<SExtInst>(GEP->getOperand(i))) ||
1431          ++NumOfVarIndices > 1)
1432         return IndexSize; // 64
1433     }
1434     return (unsigned)32;
1435   };
1436 
1437 
1438   // Trying to reduce IndexSize to 32 bits for vector 16.
1439   // By default the IndexSize is equal to pointer size.
1440   unsigned IndexSize = (VF >= 16) ? getIndexSizeInBits(Ptr, DL) :
1441     DL.getPointerSizeInBits();
1442 
1443   Type *IndexVTy = VectorType::get(IntegerType::get(SrcVTy->getContext(),
1444                                                     IndexSize), VF);
1445   std::pair<int, MVT> IdxsLT = TLI->getTypeLegalizationCost(DL, IndexVTy);
1446   std::pair<int, MVT> SrcLT = TLI->getTypeLegalizationCost(DL, SrcVTy);
1447   int SplitFactor = std::max(IdxsLT.first, SrcLT.first);
1448   if (SplitFactor > 1) {
1449     // Handle splitting of vector of pointers
1450     Type *SplitSrcTy = VectorType::get(SrcVTy->getScalarType(), VF / SplitFactor);
1451     return SplitFactor * getGSVectorCost(Opcode, SplitSrcTy, Ptr, Alignment,
1452                                          AddressSpace);
1453   }
1454 
1455   // The gather / scatter cost is given by Intel architects. It is a rough
1456   // number since we are looking at one instruction in a time.
1457   const int GSOverhead = 2;
1458   return GSOverhead + VF * getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
1459                                            Alignment, AddressSpace);
1460 }
1461 
1462 /// Return the cost of full scalarization of gather / scatter operation.
1463 ///
1464 /// Opcode - Load or Store instruction.
1465 /// SrcVTy - The type of the data vector that should be gathered or scattered.
1466 /// VariableMask - The mask is non-constant at compile time.
1467 /// Alignment - Alignment for one element.
1468 /// AddressSpace - pointer[s] address space.
1469 ///
1470 int X86TTIImpl::getGSScalarCost(unsigned Opcode, Type *SrcVTy,
1471                                 bool VariableMask, unsigned Alignment,
1472                                 unsigned AddressSpace) {
1473   unsigned VF = SrcVTy->getVectorNumElements();
1474 
1475   int MaskUnpackCost = 0;
1476   if (VariableMask) {
1477     VectorType *MaskTy =
1478       VectorType::get(Type::getInt1Ty(SrcVTy->getContext()), VF);
1479     MaskUnpackCost = getScalarizationOverhead(MaskTy, false, true);
1480     int ScalarCompareCost =
1481       getCmpSelInstrCost(Instruction::ICmp, Type::getInt1Ty(SrcVTy->getContext()),
1482                          nullptr);
1483     int BranchCost = getCFInstrCost(Instruction::Br);
1484     MaskUnpackCost += VF * (BranchCost + ScalarCompareCost);
1485   }
1486 
1487   // The cost of the scalar loads/stores.
1488   int MemoryOpCost = VF * getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
1489                                           Alignment, AddressSpace);
1490 
1491   int InsertExtractCost = 0;
1492   if (Opcode == Instruction::Load)
1493     for (unsigned i = 0; i < VF; ++i)
1494       // Add the cost of inserting each scalar load into the vector
1495       InsertExtractCost +=
1496         getVectorInstrCost(Instruction::InsertElement, SrcVTy, i);
1497   else
1498     for (unsigned i = 0; i < VF; ++i)
1499       // Add the cost of extracting each element out of the data vector
1500       InsertExtractCost +=
1501         getVectorInstrCost(Instruction::ExtractElement, SrcVTy, i);
1502 
1503   return MemoryOpCost + MaskUnpackCost + InsertExtractCost;
1504 }
1505 
1506 /// Calculate the cost of Gather / Scatter operation
1507 int X86TTIImpl::getGatherScatterOpCost(unsigned Opcode, Type *SrcVTy,
1508                                        Value *Ptr, bool VariableMask,
1509                                        unsigned Alignment) {
1510   assert(SrcVTy->isVectorTy() && "Unexpected data type for Gather/Scatter");
1511   unsigned VF = SrcVTy->getVectorNumElements();
1512   PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
1513   if (!PtrTy && Ptr->getType()->isVectorTy())
1514     PtrTy = dyn_cast<PointerType>(Ptr->getType()->getVectorElementType());
1515   assert(PtrTy && "Unexpected type for Ptr argument");
1516   unsigned AddressSpace = PtrTy->getAddressSpace();
1517 
1518   bool Scalarize = false;
1519   if ((Opcode == Instruction::Load && !isLegalMaskedGather(SrcVTy)) ||
1520       (Opcode == Instruction::Store && !isLegalMaskedScatter(SrcVTy)))
1521     Scalarize = true;
1522   // Gather / Scatter for vector 2 is not profitable on KNL / SKX
1523   // Vector-4 of gather/scatter instruction does not exist on KNL.
1524   // We can extend it to 8 elements, but zeroing upper bits of
1525   // the mask vector will add more instructions. Right now we give the scalar
1526   // cost of vector-4 for KNL. TODO: Check, maybe the gather/scatter instruction is
1527   // better in the VariableMask case.
1528   if (VF == 2 || (VF == 4 && !ST->hasVLX()))
1529     Scalarize = true;
1530 
1531   if (Scalarize)
1532     return getGSScalarCost(Opcode, SrcVTy, VariableMask, Alignment, AddressSpace);
1533 
1534   return getGSVectorCost(Opcode, SrcVTy, Ptr, Alignment, AddressSpace);
1535 }
1536 
1537 bool X86TTIImpl::isLegalMaskedLoad(Type *DataTy) {
1538   Type *ScalarTy = DataTy->getScalarType();
1539   int DataWidth = isa<PointerType>(ScalarTy) ?
1540     DL.getPointerSizeInBits() : ScalarTy->getPrimitiveSizeInBits();
1541 
1542   return (DataWidth >= 32 && ST->hasAVX()) ||
1543          (DataWidth >= 8 && ST->hasBWI());
1544 }
1545 
1546 bool X86TTIImpl::isLegalMaskedStore(Type *DataType) {
1547   return isLegalMaskedLoad(DataType);
1548 }
1549 
1550 bool X86TTIImpl::isLegalMaskedGather(Type *DataTy) {
1551   // This function is called now in two cases: from the Loop Vectorizer
1552   // and from the Scalarizer.
1553   // When the Loop Vectorizer asks about legality of the feature,
1554   // the vectorization factor is not calculated yet. The Loop Vectorizer
1555   // sends a scalar type and the decision is based on the width of the
1556   // scalar element.
1557   // Later on, the cost model will estimate usage this intrinsic based on
1558   // the vector type.
1559   // The Scalarizer asks again about legality. It sends a vector type.
1560   // In this case we can reject non-power-of-2 vectors.
1561   if (isa<VectorType>(DataTy) && !isPowerOf2_32(DataTy->getVectorNumElements()))
1562     return false;
1563   Type *ScalarTy = DataTy->getScalarType();
1564   int DataWidth = isa<PointerType>(ScalarTy) ?
1565     DL.getPointerSizeInBits() : ScalarTy->getPrimitiveSizeInBits();
1566 
1567   // AVX-512 allows gather and scatter
1568   return DataWidth >= 32 && ST->hasAVX512();
1569 }
1570 
1571 bool X86TTIImpl::isLegalMaskedScatter(Type *DataType) {
1572   return isLegalMaskedGather(DataType);
1573 }
1574 
1575 bool X86TTIImpl::areInlineCompatible(const Function *Caller,
1576                                      const Function *Callee) const {
1577   const TargetMachine &TM = getTLI()->getTargetMachine();
1578 
1579   // Work this as a subsetting of subtarget features.
1580   const FeatureBitset &CallerBits =
1581       TM.getSubtargetImpl(*Caller)->getFeatureBits();
1582   const FeatureBitset &CalleeBits =
1583       TM.getSubtargetImpl(*Callee)->getFeatureBits();
1584 
1585   // FIXME: This is likely too limiting as it will include subtarget features
1586   // that we might not care about for inlining, but it is conservatively
1587   // correct.
1588   return (CallerBits & CalleeBits) == CalleeBits;
1589 }
1590