673aefd046fe7090fc274b07d30b9198f48c7129
[oota-llvm.git] / lib / Target / X86 / X86TargetTransformInfo.cpp
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 using namespace llvm;
25
26 #define DEBUG_TYPE "x86tti"
27
28 //===----------------------------------------------------------------------===//
29 //
30 // X86 cost model.
31 //
32 //===----------------------------------------------------------------------===//
33
34 TargetTransformInfo::PopcntSupportKind
35 X86TTIImpl::getPopcntSupport(unsigned TyWidth) {
36   assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
37   // TODO: Currently the __builtin_popcount() implementation using SSE3
38   //   instructions is inefficient. Once the problem is fixed, we should
39   //   call ST->hasSSE3() instead of ST->hasPOPCNT().
40   return ST->hasPOPCNT() ? TTI::PSK_FastHardware : TTI::PSK_Software;
41 }
42
43 unsigned X86TTIImpl::getNumberOfRegisters(bool Vector) {
44   if (Vector && !ST->hasSSE1())
45     return 0;
46
47   if (ST->is64Bit()) {
48     if (Vector && ST->hasAVX512())
49       return 32;
50     return 16;
51   }
52   return 8;
53 }
54
55 unsigned X86TTIImpl::getRegisterBitWidth(bool Vector) {
56   if (Vector) {
57     if (ST->hasAVX512()) return 512;
58     if (ST->hasAVX()) return 256;
59     if (ST->hasSSE1()) return 128;
60     return 0;
61   }
62
63   if (ST->is64Bit())
64     return 64;
65   return 32;
66
67 }
68
69 unsigned X86TTIImpl::getMaxInterleaveFactor(unsigned VF) {
70   // If the loop will not be vectorized, don't interleave the loop.
71   // Let regular unroll to unroll the loop, which saves the overflow
72   // check and memory check cost.
73   if (VF == 1)
74     return 1;
75
76   if (ST->isAtom())
77     return 1;
78
79   // Sandybridge and Haswell have multiple execution ports and pipelined
80   // vector units.
81   if (ST->hasAVX())
82     return 4;
83
84   return 2;
85 }
86
87 unsigned X86TTIImpl::getArithmeticInstrCost(
88     unsigned Opcode, Type *Ty, TTI::OperandValueKind Op1Info,
89     TTI::OperandValueKind Op2Info, TTI::OperandValueProperties Opd1PropInfo,
90     TTI::OperandValueProperties Opd2PropInfo) {
91   // Legalize the type.
92   std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
93
94   int ISD = TLI->InstructionOpcodeToISD(Opcode);
95   assert(ISD && "Invalid opcode");
96
97   if (ISD == ISD::SDIV &&
98       Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
99       Opd2PropInfo == TargetTransformInfo::OP_PowerOf2) {
100     // On X86, vector signed division by constants power-of-two are
101     // normally expanded to the sequence SRA + SRL + ADD + SRA.
102     // The OperandValue properties many not be same as that of previous
103     // operation;conservatively assume OP_None.
104     unsigned Cost =
105         2 * getArithmeticInstrCost(Instruction::AShr, Ty, Op1Info, Op2Info,
106                                    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<MVT::SimpleValueType>
119   AVX2UniformConstCostTable[] = {
120     { ISD::SRA,  MVT::v4i64,   4 }, // 2 x psrad + shuffle.
121
122     { ISD::SDIV, MVT::v16i16,  6 }, // vpmulhw sequence
123     { ISD::UDIV, MVT::v16i16,  6 }, // vpmulhuw sequence
124     { ISD::SDIV, MVT::v8i32,  15 }, // vpmuldq sequence
125     { ISD::UDIV, MVT::v8i32,  15 }, // vpmuludq sequence
126   };
127
128   if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
129       ST->hasAVX2()) {
130     int Idx = CostTableLookup(AVX2UniformConstCostTable, ISD, LT.second);
131     if (Idx != -1)
132       return LT.first * AVX2UniformConstCostTable[Idx].Cost;
133   }
134
135   static const CostTblEntry<MVT::SimpleValueType> AVX512CostTable[] = {
136     { ISD::SHL,     MVT::v16i32,    1 },
137     { ISD::SRL,     MVT::v16i32,    1 },
138     { ISD::SRA,     MVT::v16i32,    1 },
139     { ISD::SHL,     MVT::v8i64,    1 },
140     { ISD::SRL,     MVT::v8i64,    1 },
141     { ISD::SRA,     MVT::v8i64,    1 },
142   };
143
144   static const CostTblEntry<MVT::SimpleValueType> AVX2CostTable[] = {
145     // Shifts on v4i64/v8i32 on AVX2 is legal even though we declare to
146     // customize them to detect the cases where shift amount is a scalar one.
147     { ISD::SHL,     MVT::v4i32,    1 },
148     { ISD::SRL,     MVT::v4i32,    1 },
149     { ISD::SRA,     MVT::v4i32,    1 },
150     { ISD::SHL,     MVT::v8i32,    1 },
151     { ISD::SRL,     MVT::v8i32,    1 },
152     { ISD::SRA,     MVT::v8i32,    1 },
153     { ISD::SHL,     MVT::v2i64,    1 },
154     { ISD::SRL,     MVT::v2i64,    1 },
155     { ISD::SHL,     MVT::v4i64,    1 },
156     { ISD::SRL,     MVT::v4i64,    1 },
157
158     { ISD::SHL,  MVT::v32i8,      11 }, // vpblendvb sequence.
159     { ISD::SHL,  MVT::v16i16,     10 }, // extend/vpsrlvd/pack sequence.
160
161     { ISD::SRL,  MVT::v32i8,      11 }, // vpblendvb sequence.
162     { ISD::SRL,  MVT::v16i16,     10 }, // extend/vpsrlvd/pack sequence.
163
164     { ISD::SRA,  MVT::v32i8,      24 }, // vpblendvb sequence.
165     { ISD::SRA,  MVT::v16i16,     10 }, // extend/vpsravd/pack sequence.
166     { ISD::SRA,  MVT::v2i64,       4 }, // srl/xor/sub sequence.
167     { ISD::SRA,  MVT::v4i64,       4 }, // srl/xor/sub sequence.
168
169     // Vectorizing division is a bad idea. See the SSE2 table for more comments.
170     { ISD::SDIV,  MVT::v32i8,  32*20 },
171     { ISD::SDIV,  MVT::v16i16, 16*20 },
172     { ISD::SDIV,  MVT::v8i32,  8*20 },
173     { ISD::SDIV,  MVT::v4i64,  4*20 },
174     { ISD::UDIV,  MVT::v32i8,  32*20 },
175     { ISD::UDIV,  MVT::v16i16, 16*20 },
176     { ISD::UDIV,  MVT::v8i32,  8*20 },
177     { ISD::UDIV,  MVT::v4i64,  4*20 },
178   };
179
180   if (ST->hasAVX512()) {
181     int Idx = CostTableLookup(AVX512CostTable, ISD, LT.second);
182     if (Idx != -1)
183       return LT.first * AVX512CostTable[Idx].Cost;
184   }
185   // Look for AVX2 lowering tricks.
186   if (ST->hasAVX2()) {
187     if (ISD == ISD::SHL && LT.second == MVT::v16i16 &&
188         (Op2Info == TargetTransformInfo::OK_UniformConstantValue ||
189          Op2Info == TargetTransformInfo::OK_NonUniformConstantValue))
190       // On AVX2, a packed v16i16 shift left by a constant build_vector
191       // is lowered into a vector multiply (vpmullw).
192       return LT.first;
193
194     int Idx = CostTableLookup(AVX2CostTable, ISD, LT.second);
195     if (Idx != -1)
196       return LT.first * AVX2CostTable[Idx].Cost;
197   }
198
199   static const CostTblEntry<MVT::SimpleValueType>
200   SSE2UniformConstCostTable[] = {
201     // We don't correctly identify costs of casts because they are marked as
202     // custom.
203     // Constant splats are cheaper for the following instructions.
204     { ISD::SHL,  MVT::v16i8,  1 }, // psllw.
205     { ISD::SHL,  MVT::v8i16,  1 }, // psllw.
206     { ISD::SHL,  MVT::v4i32,  1 }, // pslld
207     { ISD::SHL,  MVT::v2i64,  1 }, // psllq.
208
209     { ISD::SRL,  MVT::v16i8,  1 }, // psrlw.
210     { ISD::SRL,  MVT::v8i16,  1 }, // psrlw.
211     { ISD::SRL,  MVT::v4i32,  1 }, // psrld.
212     { ISD::SRL,  MVT::v2i64,  1 }, // psrlq.
213
214     { ISD::SRA,  MVT::v16i8,  4 }, // psrlw, pand, pxor, psubb.
215     { ISD::SRA,  MVT::v8i16,  1 }, // psraw.
216     { ISD::SRA,  MVT::v4i32,  1 }, // psrad.
217     { ISD::SRA,  MVT::v2i64,  4 }, // 2 x psrad + shuffle.
218
219     { ISD::SDIV, MVT::v8i16,  6 }, // pmulhw sequence
220     { ISD::UDIV, MVT::v8i16,  6 }, // pmulhuw sequence
221     { ISD::SDIV, MVT::v4i32, 19 }, // pmuludq sequence
222     { ISD::UDIV, MVT::v4i32, 15 }, // pmuludq sequence
223   };
224
225   if (Op2Info == TargetTransformInfo::OK_UniformConstantValue &&
226       ST->hasSSE2()) {
227     // pmuldq sequence.
228     if (ISD == ISD::SDIV && LT.second == MVT::v4i32 && ST->hasSSE41())
229       return LT.first * 15;
230
231     int Idx = CostTableLookup(SSE2UniformConstCostTable, ISD, LT.second);
232     if (Idx != -1)
233       return LT.first * SSE2UniformConstCostTable[Idx].Cost;
234   }
235
236   if (ISD == ISD::SHL &&
237       Op2Info == TargetTransformInfo::OK_NonUniformConstantValue) {
238     EVT VT = LT.second;
239     if ((VT == MVT::v8i16 && ST->hasSSE2()) ||
240         (VT == MVT::v4i32 && ST->hasSSE41()))
241       // Vector shift left by non uniform constant can be lowered
242       // into vector multiply (pmullw/pmulld).
243       return LT.first;
244     if (VT == MVT::v4i32 && ST->hasSSE2())
245       // A vector shift left by non uniform constant is converted
246       // into a vector multiply; the new multiply is eventually
247       // lowered into a sequence of shuffles and 2 x pmuludq.
248       ISD = ISD::MUL;
249   }
250
251   static const CostTblEntry<MVT::SimpleValueType> SSE2CostTable[] = {
252     // We don't correctly identify costs of casts because they are marked as
253     // custom.
254     // For some cases, where the shift amount is a scalar we would be able
255     // to generate better code. Unfortunately, when this is the case the value
256     // (the splat) will get hoisted out of the loop, thereby making it invisible
257     // to ISel. The cost model must return worst case assumptions because it is
258     // used for vectorization and we don't want to make vectorized code worse
259     // than scalar code.
260     { ISD::SHL,  MVT::v16i8,    26 }, // cmpgtb sequence.
261     { ISD::SHL,  MVT::v8i16,    32 }, // cmpgtb sequence.
262     { ISD::SHL,  MVT::v4i32,   2*5 }, // We optimized this using mul.
263     { ISD::SHL,  MVT::v2i64,     4 }, // splat+shuffle sequence.
264     { ISD::SHL,  MVT::v4i64,     8 }, // splat+shuffle sequence.
265
266     { ISD::SRL,  MVT::v16i8,    26 }, // cmpgtb sequence.
267     { ISD::SRL,  MVT::v8i16,    32 }, // cmpgtb sequence.
268     { ISD::SRL,  MVT::v4i32,    16 }, // Shift each lane + blend.
269     { ISD::SRL,  MVT::v2i64,     4 }, // splat+shuffle sequence.
270
271     { ISD::SRA,  MVT::v16i8,    54 }, // unpacked cmpgtb sequence.
272     { ISD::SRA,  MVT::v8i16,    32 }, // cmpgtb sequence.
273     { ISD::SRA,  MVT::v4i32,    16 }, // Shift each lane + blend.
274     { ISD::SRA,  MVT::v2i64,    12 }, // srl/xor/sub sequence.
275
276     // It is not a good idea to vectorize division. We have to scalarize it and
277     // in the process we will often end up having to spilling regular
278     // registers. The overhead of division is going to dominate most kernels
279     // anyways so try hard to prevent vectorization of division - it is
280     // generally a bad idea. Assume somewhat arbitrarily that we have to be able
281     // to hide "20 cycles" for each lane.
282     { ISD::SDIV,  MVT::v16i8,  16*20 },
283     { ISD::SDIV,  MVT::v8i16,  8*20 },
284     { ISD::SDIV,  MVT::v4i32,  4*20 },
285     { ISD::SDIV,  MVT::v2i64,  2*20 },
286     { ISD::UDIV,  MVT::v16i8,  16*20 },
287     { ISD::UDIV,  MVT::v8i16,  8*20 },
288     { ISD::UDIV,  MVT::v4i32,  4*20 },
289     { ISD::UDIV,  MVT::v2i64,  2*20 },
290   };
291
292   if (ST->hasSSE2()) {
293     int Idx = CostTableLookup(SSE2CostTable, ISD, LT.second);
294     if (Idx != -1)
295       return LT.first * SSE2CostTable[Idx].Cost;
296   }
297
298   static const CostTblEntry<MVT::SimpleValueType> AVX1CostTable[] = {
299     // We don't have to scalarize unsupported ops. We can issue two half-sized
300     // operations and we only need to extract the upper YMM half.
301     // Two ops + 1 extract + 1 insert = 4.
302     { ISD::MUL,     MVT::v16i16,   4 },
303     { ISD::MUL,     MVT::v8i32,    4 },
304     { ISD::SUB,     MVT::v8i32,    4 },
305     { ISD::ADD,     MVT::v8i32,    4 },
306     { ISD::SUB,     MVT::v4i64,    4 },
307     { ISD::ADD,     MVT::v4i64,    4 },
308     // A v4i64 multiply is custom lowered as two split v2i64 vectors that then
309     // are lowered as a series of long multiplies(3), shifts(4) and adds(2)
310     // Because we believe v4i64 to be a legal type, we must also include the
311     // split factor of two in the cost table. Therefore, the cost here is 18
312     // instead of 9.
313     { ISD::MUL,     MVT::v4i64,    18 },
314   };
315
316   // Look for AVX1 lowering tricks.
317   if (ST->hasAVX() && !ST->hasAVX2()) {
318     EVT VT = LT.second;
319
320     // v16i16 and v8i32 shifts by non-uniform constants are lowered into a
321     // sequence of extract + two vector multiply + insert.
322     if (ISD == ISD::SHL && (VT == MVT::v8i32 || VT == MVT::v16i16) &&
323         Op2Info == TargetTransformInfo::OK_NonUniformConstantValue)
324       ISD = ISD::MUL;
325
326     int Idx = CostTableLookup(AVX1CostTable, ISD, VT);
327     if (Idx != -1)
328       return LT.first * AVX1CostTable[Idx].Cost;
329   }
330
331   // Custom lowering of vectors.
332   static const CostTblEntry<MVT::SimpleValueType> CustomLowered[] = {
333     // A v2i64/v4i64 and multiply is custom lowered as a series of long
334     // multiplies(3), shifts(4) and adds(2).
335     { ISD::MUL,     MVT::v2i64,    9 },
336     { ISD::MUL,     MVT::v4i64,    9 },
337   };
338   int Idx = CostTableLookup(CustomLowered, ISD, LT.second);
339   if (Idx != -1)
340     return LT.first * CustomLowered[Idx].Cost;
341
342   // Special lowering of v4i32 mul on sse2, sse3: Lower v4i32 mul as 2x shuffle,
343   // 2x pmuludq, 2x shuffle.
344   if (ISD == ISD::MUL && LT.second == MVT::v4i32 && ST->hasSSE2() &&
345       !ST->hasSSE41())
346     return LT.first * 6;
347
348   // Fallback to the default implementation.
349   return BaseT::getArithmeticInstrCost(Opcode, Ty, Op1Info, Op2Info);
350 }
351
352 unsigned X86TTIImpl::getShuffleCost(TTI::ShuffleKind Kind, Type *Tp, int Index,
353                                     Type *SubTp) {
354   // We only estimate the cost of reverse and alternate shuffles.
355   if (Kind != TTI::SK_Reverse && Kind != TTI::SK_Alternate)
356     return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
357
358   if (Kind == TTI::SK_Reverse) {
359     std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
360     unsigned Cost = 1;
361     if (LT.second.getSizeInBits() > 128)
362       Cost = 3; // Extract + insert + copy.
363
364     // Multiple by the number of parts.
365     return Cost * LT.first;
366   }
367
368   if (Kind == TTI::SK_Alternate) {
369     // 64-bit packed float vectors (v2f32) are widened to type v4f32.
370     // 64-bit packed integer vectors (v2i32) are promoted to type v2i64.
371     std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
372
373     // The backend knows how to generate a single VEX.256 version of
374     // instruction VPBLENDW if the target supports AVX2.
375     if (ST->hasAVX2() && LT.second == MVT::v16i16)
376       return LT.first;
377
378     static const CostTblEntry<MVT::SimpleValueType> AVXAltShuffleTbl[] = {
379       {ISD::VECTOR_SHUFFLE, MVT::v4i64, 1},  // vblendpd
380       {ISD::VECTOR_SHUFFLE, MVT::v4f64, 1},  // vblendpd
381
382       {ISD::VECTOR_SHUFFLE, MVT::v8i32, 1},  // vblendps
383       {ISD::VECTOR_SHUFFLE, MVT::v8f32, 1},  // vblendps
384
385       // This shuffle is custom lowered into a sequence of:
386       //  2x  vextractf128 , 2x vpblendw , 1x vinsertf128
387       {ISD::VECTOR_SHUFFLE, MVT::v16i16, 5},
388
389       // This shuffle is custom lowered into a long sequence of:
390       //  2x vextractf128 , 4x vpshufb , 2x vpor ,  1x vinsertf128
391       {ISD::VECTOR_SHUFFLE, MVT::v32i8, 9}
392     };
393
394     if (ST->hasAVX()) {
395       int Idx = CostTableLookup(AVXAltShuffleTbl, ISD::VECTOR_SHUFFLE, LT.second);
396       if (Idx != -1)
397         return LT.first * AVXAltShuffleTbl[Idx].Cost;
398     }
399
400     static const CostTblEntry<MVT::SimpleValueType> SSE41AltShuffleTbl[] = {
401       // These are lowered into movsd.
402       {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
403       {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
404
405       // packed float vectors with four elements are lowered into BLENDI dag
406       // nodes. A v4i32/v4f32 BLENDI generates a single 'blendps'/'blendpd'.
407       {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
408       {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
409
410       // This shuffle generates a single pshufw.
411       {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
412
413       // There is no instruction that matches a v16i8 alternate shuffle.
414       // The backend will expand it into the sequence 'pshufb + pshufb + or'.
415       {ISD::VECTOR_SHUFFLE, MVT::v16i8, 3}
416     };
417
418     if (ST->hasSSE41()) {
419       int Idx = CostTableLookup(SSE41AltShuffleTbl, ISD::VECTOR_SHUFFLE, LT.second);
420       if (Idx != -1)
421         return LT.first * SSE41AltShuffleTbl[Idx].Cost;
422     }
423
424     static const CostTblEntry<MVT::SimpleValueType> SSSE3AltShuffleTbl[] = {
425       {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},  // movsd
426       {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},  // movsd
427
428       // SSE3 doesn't have 'blendps'. The following shuffles are expanded into
429       // the sequence 'shufps + pshufd'
430       {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
431       {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
432
433       {ISD::VECTOR_SHUFFLE, MVT::v8i16, 3}, // pshufb + pshufb + or
434       {ISD::VECTOR_SHUFFLE, MVT::v16i8, 3}  // pshufb + pshufb + or
435     };
436
437     if (ST->hasSSSE3()) {
438       int Idx = CostTableLookup(SSSE3AltShuffleTbl, ISD::VECTOR_SHUFFLE, LT.second);
439       if (Idx != -1)
440         return LT.first * SSSE3AltShuffleTbl[Idx].Cost;
441     }
442
443     static const CostTblEntry<MVT::SimpleValueType> SSEAltShuffleTbl[] = {
444       {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},  // movsd
445       {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},  // movsd
446
447       {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2}, // shufps + pshufd
448       {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2}, // shufps + pshufd
449
450       // This is expanded into a long sequence of four extract + four insert.
451       {ISD::VECTOR_SHUFFLE, MVT::v8i16, 8}, // 4 x pextrw + 4 pinsrw.
452
453       // 8 x (pinsrw + pextrw + and + movb + movzb + or)
454       {ISD::VECTOR_SHUFFLE, MVT::v16i8, 48}
455     };
456
457     // Fall-back (SSE3 and SSE2).
458     int Idx = CostTableLookup(SSEAltShuffleTbl, ISD::VECTOR_SHUFFLE, LT.second);
459     if (Idx != -1)
460       return LT.first * SSEAltShuffleTbl[Idx].Cost;
461     return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
462   }
463
464   return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
465 }
466
467 unsigned X86TTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) {
468   int ISD = TLI->InstructionOpcodeToISD(Opcode);
469   assert(ISD && "Invalid opcode");
470
471   static const TypeConversionCostTblEntry<MVT::SimpleValueType>
472   AVX512ConversionTbl[] = {
473     { ISD::FP_EXTEND, MVT::v8f64,   MVT::v8f32,  1 },
474     { ISD::FP_EXTEND, MVT::v8f64,   MVT::v16f32, 3 },
475     { ISD::FP_ROUND,  MVT::v8f32,   MVT::v8f64,  1 },
476     { ISD::FP_ROUND,  MVT::v16f32,  MVT::v8f64,  3 },
477
478     { ISD::TRUNCATE,  MVT::v16i8,   MVT::v16i32, 1 },
479     { ISD::TRUNCATE,  MVT::v16i16,  MVT::v16i32, 1 },
480     { ISD::TRUNCATE,  MVT::v8i16,   MVT::v8i64,  1 },
481     { ISD::TRUNCATE,  MVT::v8i32,   MVT::v8i64,  1 },
482     { ISD::TRUNCATE,  MVT::v16i32,  MVT::v8i64,  4 },
483
484     // v16i1 -> v16i32 - load + broadcast
485     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i1,  2 },
486     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i1,  2 },
487
488     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8,  1 },
489     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8,  1 },
490     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i16, 1 },
491     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i16, 1 },
492     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v16i32, 3 },
493     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v16i32, 3 },
494
495     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i1,  3 },
496     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i8,  2 },
497     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i16, 2 },
498     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i32, 1 },
499     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i1,   4 },
500     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i16,  2 },
501     { ISD::SINT_TO_FP,  MVT::v8f64,  MVT::v8i32,  1 },
502   };
503
504   static const TypeConversionCostTblEntry<MVT::SimpleValueType>
505   AVX2ConversionTbl[] = {
506     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8,  1 },
507     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8,  1 },
508     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i1,   3 },
509     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i1,   3 },
510     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i8,   3 },
511     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i8,   3 },
512     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16,  1 },
513     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16,  1 },
514     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i1,   3 },
515     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i1,   3 },
516     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i8,   3 },
517     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i8,   3 },
518     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i16,  3 },
519     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i16,  3 },
520     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i32,  1 },
521     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i32,  1 },
522
523     { ISD::TRUNCATE,    MVT::v4i8,   MVT::v4i64,  2 },
524     { ISD::TRUNCATE,    MVT::v4i16,  MVT::v4i64,  2 },
525     { ISD::TRUNCATE,    MVT::v4i32,  MVT::v4i64,  2 },
526     { ISD::TRUNCATE,    MVT::v8i8,   MVT::v8i32,  2 },
527     { ISD::TRUNCATE,    MVT::v8i16,  MVT::v8i32,  2 },
528     { ISD::TRUNCATE,    MVT::v8i32,  MVT::v8i64,  4 },
529
530     { ISD::FP_EXTEND,   MVT::v8f64,  MVT::v8f32,  3 },
531     { ISD::FP_ROUND,    MVT::v8f32,  MVT::v8f64,  3 },
532
533     { ISD::UINT_TO_FP,  MVT::v8f32,  MVT::v8i32,  8 },
534   };
535
536   static const TypeConversionCostTblEntry<MVT::SimpleValueType>
537   AVXConversionTbl[] = {
538     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 4 },
539     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 4 },
540     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i1,  7 },
541     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i1,  4 },
542     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i8,  7 },
543     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i8,  4 },
544     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16, 4 },
545     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16, 4 },
546     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i1,  6 },
547     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i1,  4 },
548     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i8,  6 },
549     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i8,  4 },
550     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i16, 6 },
551     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i16, 3 },
552     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i32, 4 },
553     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i32, 4 },
554
555     { ISD::TRUNCATE,    MVT::v4i8,  MVT::v4i64,  4 },
556     { ISD::TRUNCATE,    MVT::v4i16, MVT::v4i64,  4 },
557     { ISD::TRUNCATE,    MVT::v4i32, MVT::v4i64,  4 },
558     { ISD::TRUNCATE,    MVT::v8i8,  MVT::v8i32,  4 },
559     { ISD::TRUNCATE,    MVT::v8i16, MVT::v8i32,  5 },
560     { ISD::TRUNCATE,    MVT::v16i8, MVT::v16i16, 4 },
561     { ISD::TRUNCATE,    MVT::v8i32, MVT::v8i64,  9 },
562
563     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i1,  8 },
564     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i8,  8 },
565     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i16, 5 },
566     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i32, 1 },
567     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i1,  3 },
568     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i8,  3 },
569     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i16, 3 },
570     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i32, 1 },
571     { ISD::SINT_TO_FP,  MVT::v4f64, MVT::v4i1,  3 },
572     { ISD::SINT_TO_FP,  MVT::v4f64, MVT::v4i8,  3 },
573     { ISD::SINT_TO_FP,  MVT::v4f64, MVT::v4i16, 3 },
574     { ISD::SINT_TO_FP,  MVT::v4f64, MVT::v4i32, 1 },
575
576     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i1,  6 },
577     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i8,  5 },
578     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i16, 5 },
579     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i32, 9 },
580     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i1,  7 },
581     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i8,  2 },
582     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i16, 2 },
583     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i32, 6 },
584     { ISD::UINT_TO_FP,  MVT::v4f64, MVT::v4i1,  7 },
585     { ISD::UINT_TO_FP,  MVT::v4f64, MVT::v4i8,  2 },
586     { ISD::UINT_TO_FP,  MVT::v4f64, MVT::v4i16, 2 },
587     { ISD::UINT_TO_FP,  MVT::v4f64, MVT::v4i32, 6 },
588     // The generic code to compute the scalar overhead is currently broken.
589     // Workaround this limitation by estimating the scalarization overhead
590     // here. We have roughly 10 instructions per scalar element.
591     // Multiply that by the vector width.
592     // FIXME: remove that when PR19268 is fixed.
593     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i64, 2*10 },
594     { ISD::UINT_TO_FP,  MVT::v4f64, MVT::v4i64, 4*10 },
595
596     { ISD::FP_TO_SINT,  MVT::v8i8,  MVT::v8f32, 7 },
597     { ISD::FP_TO_SINT,  MVT::v4i8,  MVT::v4f32, 1 },
598     // This node is expanded into scalarized operations but BasicTTI is overly
599     // optimistic estimating its cost.  It computes 3 per element (one
600     // vector-extract, one scalar conversion and one vector-insert).  The
601     // problem is that the inserts form a read-modify-write chain so latency
602     // should be factored in too.  Inflating the cost per element by 1.
603     { ISD::FP_TO_UINT,  MVT::v8i32, MVT::v8f32, 8*4 },
604     { ISD::FP_TO_UINT,  MVT::v4i32, MVT::v4f64, 4*4 },
605   };
606
607   static const TypeConversionCostTblEntry<MVT::SimpleValueType>
608   SSE2ConvTbl[] = {
609     // These are somewhat magic numbers justified by looking at the output of
610     // Intel's IACA, running some kernels and making sure when we take
611     // legalization into account the throughput will be overestimated.
612     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 2*10 },
613     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v4i32, 4*10 },
614     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v8i16, 8*10 },
615     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v16i8, 16*10 },
616     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i64, 2*10 },
617     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v4i32, 4*10 },
618     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v8i16, 8*10 },
619     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v16i8, 16*10 },
620     // There are faster sequences for float conversions.
621     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v2i64, 15 },
622     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 8 },
623     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v8i16, 15 },
624     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v16i8, 8 },
625     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v2i64, 15 },
626     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 15 },
627     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v8i16, 15 },
628     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v16i8, 8 },
629   };
630
631   std::pair<unsigned, MVT> LTSrc = TLI->getTypeLegalizationCost(DL, Src);
632   std::pair<unsigned, MVT> LTDest = TLI->getTypeLegalizationCost(DL, Dst);
633
634   if (ST->hasSSE2() && !ST->hasAVX()) {
635     int Idx =
636         ConvertCostTableLookup(SSE2ConvTbl, ISD, LTDest.second, LTSrc.second);
637     if (Idx != -1)
638       return LTSrc.first * SSE2ConvTbl[Idx].Cost;
639   }
640
641   if (ST->hasAVX512()) {
642     int Idx = ConvertCostTableLookup(AVX512ConversionTbl, ISD, LTDest.second,
643                                      LTSrc.second);
644     if (Idx != -1)
645       return AVX512ConversionTbl[Idx].Cost;
646   }
647
648   EVT SrcTy = TLI->getValueType(DL, Src);
649   EVT DstTy = TLI->getValueType(DL, Dst);
650
651   // The function getSimpleVT only handles simple value types.
652   if (!SrcTy.isSimple() || !DstTy.isSimple())
653     return BaseT::getCastInstrCost(Opcode, Dst, Src);
654
655   if (ST->hasAVX2()) {
656     int Idx = ConvertCostTableLookup(AVX2ConversionTbl, ISD,
657                                      DstTy.getSimpleVT(), SrcTy.getSimpleVT());
658     if (Idx != -1)
659       return AVX2ConversionTbl[Idx].Cost;
660   }
661
662   if (ST->hasAVX()) {
663     int Idx = ConvertCostTableLookup(AVXConversionTbl, ISD, DstTy.getSimpleVT(),
664                                      SrcTy.getSimpleVT());
665     if (Idx != -1)
666       return AVXConversionTbl[Idx].Cost;
667   }
668
669   return BaseT::getCastInstrCost(Opcode, Dst, Src);
670 }
671
672 unsigned X86TTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
673                                         Type *CondTy) {
674   // Legalize the type.
675   std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
676
677   MVT MTy = LT.second;
678
679   int ISD = TLI->InstructionOpcodeToISD(Opcode);
680   assert(ISD && "Invalid opcode");
681
682   static const CostTblEntry<MVT::SimpleValueType> SSE42CostTbl[] = {
683     { ISD::SETCC,   MVT::v2f64,   1 },
684     { ISD::SETCC,   MVT::v4f32,   1 },
685     { ISD::SETCC,   MVT::v2i64,   1 },
686     { ISD::SETCC,   MVT::v4i32,   1 },
687     { ISD::SETCC,   MVT::v8i16,   1 },
688     { ISD::SETCC,   MVT::v16i8,   1 },
689   };
690
691   static const CostTblEntry<MVT::SimpleValueType> AVX1CostTbl[] = {
692     { ISD::SETCC,   MVT::v4f64,   1 },
693     { ISD::SETCC,   MVT::v8f32,   1 },
694     // AVX1 does not support 8-wide integer compare.
695     { ISD::SETCC,   MVT::v4i64,   4 },
696     { ISD::SETCC,   MVT::v8i32,   4 },
697     { ISD::SETCC,   MVT::v16i16,  4 },
698     { ISD::SETCC,   MVT::v32i8,   4 },
699   };
700
701   static const CostTblEntry<MVT::SimpleValueType> AVX2CostTbl[] = {
702     { ISD::SETCC,   MVT::v4i64,   1 },
703     { ISD::SETCC,   MVT::v8i32,   1 },
704     { ISD::SETCC,   MVT::v16i16,  1 },
705     { ISD::SETCC,   MVT::v32i8,   1 },
706   };
707
708   static const CostTblEntry<MVT::SimpleValueType> AVX512CostTbl[] = {
709     { ISD::SETCC,   MVT::v8i64,   1 },
710     { ISD::SETCC,   MVT::v16i32,  1 },
711     { ISD::SETCC,   MVT::v8f64,   1 },
712     { ISD::SETCC,   MVT::v16f32,  1 },
713   };
714
715   if (ST->hasAVX512()) {
716     int Idx = CostTableLookup(AVX512CostTbl, ISD, MTy);
717     if (Idx != -1)
718       return LT.first * AVX512CostTbl[Idx].Cost;
719   }
720
721   if (ST->hasAVX2()) {
722     int Idx = CostTableLookup(AVX2CostTbl, ISD, MTy);
723     if (Idx != -1)
724       return LT.first * AVX2CostTbl[Idx].Cost;
725   }
726
727   if (ST->hasAVX()) {
728     int Idx = CostTableLookup(AVX1CostTbl, ISD, MTy);
729     if (Idx != -1)
730       return LT.first * AVX1CostTbl[Idx].Cost;
731   }
732
733   if (ST->hasSSE42()) {
734     int Idx = CostTableLookup(SSE42CostTbl, ISD, MTy);
735     if (Idx != -1)
736       return LT.first * SSE42CostTbl[Idx].Cost;
737   }
738
739   return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy);
740 }
741
742 unsigned X86TTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val,
743                                         unsigned Index) {
744   assert(Val->isVectorTy() && "This must be a vector type");
745
746   if (Index != -1U) {
747     // Legalize the type.
748     std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, Val);
749
750     // This type is legalized to a scalar type.
751     if (!LT.second.isVector())
752       return 0;
753
754     // The type may be split. Normalize the index to the new type.
755     unsigned Width = LT.second.getVectorNumElements();
756     Index = Index % Width;
757
758     // Floating point scalars are already located in index #0.
759     if (Val->getScalarType()->isFloatingPointTy() && Index == 0)
760       return 0;
761   }
762
763   return BaseT::getVectorInstrCost(Opcode, Val, Index);
764 }
765
766 unsigned X86TTIImpl::getScalarizationOverhead(Type *Ty, bool Insert,
767                                               bool Extract) {
768   assert (Ty->isVectorTy() && "Can only scalarize vectors");
769   unsigned Cost = 0;
770
771   for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
772     if (Insert)
773       Cost += getVectorInstrCost(Instruction::InsertElement, Ty, i);
774     if (Extract)
775       Cost += getVectorInstrCost(Instruction::ExtractElement, Ty, i);
776   }
777
778   return Cost;
779 }
780
781 unsigned X86TTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
782                                      unsigned Alignment,
783                                      unsigned AddressSpace) {
784   // Handle non-power-of-two vectors such as <3 x float>
785   if (VectorType *VTy = dyn_cast<VectorType>(Src)) {
786     unsigned NumElem = VTy->getVectorNumElements();
787
788     // Handle a few common cases:
789     // <3 x float>
790     if (NumElem == 3 && VTy->getScalarSizeInBits() == 32)
791       // Cost = 64 bit store + extract + 32 bit store.
792       return 3;
793
794     // <3 x double>
795     if (NumElem == 3 && VTy->getScalarSizeInBits() == 64)
796       // Cost = 128 bit store + unpack + 64 bit store.
797       return 3;
798
799     // Assume that all other non-power-of-two numbers are scalarized.
800     if (!isPowerOf2_32(NumElem)) {
801       unsigned Cost = BaseT::getMemoryOpCost(Opcode, VTy->getScalarType(),
802                                              Alignment, AddressSpace);
803       unsigned SplitCost = getScalarizationOverhead(Src,
804                                                     Opcode == Instruction::Load,
805                                                     Opcode==Instruction::Store);
806       return NumElem * Cost + SplitCost;
807     }
808   }
809
810   // Legalize the type.
811   std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
812   assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
813          "Invalid Opcode");
814
815   // Each load/store unit costs 1.
816   unsigned Cost = LT.first * 1;
817
818   // On Sandybridge 256bit load/stores are double pumped
819   // (but not on Haswell).
820   if (LT.second.getSizeInBits() > 128 && !ST->hasAVX2())
821     Cost*=2;
822
823   return Cost;
824 }
825
826 unsigned X86TTIImpl::getMaskedMemoryOpCost(unsigned Opcode, Type *SrcTy,
827                                            unsigned Alignment,
828                                            unsigned AddressSpace) {
829   VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy);
830   if (!SrcVTy)
831     // To calculate scalar take the regular cost, without mask
832     return getMemoryOpCost(Opcode, SrcTy, Alignment, AddressSpace);
833
834   unsigned NumElem = SrcVTy->getVectorNumElements();
835   VectorType *MaskTy =
836     VectorType::get(Type::getInt8Ty(getGlobalContext()), NumElem);
837   if ((Opcode == Instruction::Load && !isLegalMaskedLoad(SrcVTy, 1)) ||
838       (Opcode == Instruction::Store && !isLegalMaskedStore(SrcVTy, 1)) ||
839       !isPowerOf2_32(NumElem)) {
840     // Scalarization
841     unsigned MaskSplitCost = getScalarizationOverhead(MaskTy, false, true);
842     unsigned ScalarCompareCost =
843       getCmpSelInstrCost(Instruction::ICmp,
844                          Type::getInt8Ty(getGlobalContext()), NULL);
845     unsigned BranchCost = getCFInstrCost(Instruction::Br);
846     unsigned MaskCmpCost = NumElem * (BranchCost + ScalarCompareCost);
847
848     unsigned ValueSplitCost =
849       getScalarizationOverhead(SrcVTy, Opcode == Instruction::Load,
850                                Opcode == Instruction::Store);
851     unsigned MemopCost =
852         NumElem * BaseT::getMemoryOpCost(Opcode, SrcVTy->getScalarType(),
853                                          Alignment, AddressSpace);
854     return MemopCost + ValueSplitCost + MaskSplitCost + MaskCmpCost;
855   }
856
857   // Legalize the type.
858   std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, SrcVTy);
859   unsigned Cost = 0;
860   if (LT.second != TLI->getValueType(DL, SrcVTy).getSimpleVT() &&
861       LT.second.getVectorNumElements() == NumElem)
862     // Promotion requires expand/truncate for data and a shuffle for mask.
863     Cost += getShuffleCost(TTI::SK_Alternate, SrcVTy, 0, 0) +
864             getShuffleCost(TTI::SK_Alternate, MaskTy, 0, 0);
865
866   else if (LT.second.getVectorNumElements() > NumElem) {
867     VectorType *NewMaskTy = VectorType::get(MaskTy->getVectorElementType(),
868                                             LT.second.getVectorNumElements());
869     // Expanding requires fill mask with zeroes
870     Cost += getShuffleCost(TTI::SK_InsertSubvector, NewMaskTy, 0, MaskTy);
871   }
872   if (!ST->hasAVX512())
873     return Cost + LT.first*4; // Each maskmov costs 4
874
875   // AVX-512 masked load/store is cheapper
876   return Cost+LT.first;
877 }
878
879 unsigned X86TTIImpl::getAddressComputationCost(Type *Ty, bool IsComplex) {
880   // Address computations in vectorized code with non-consecutive addresses will
881   // likely result in more instructions compared to scalar code where the
882   // computation can more often be merged into the index mode. The resulting
883   // extra micro-ops can significantly decrease throughput.
884   unsigned NumVectorInstToHideOverhead = 10;
885
886   if (Ty->isVectorTy() && IsComplex)
887     return NumVectorInstToHideOverhead;
888
889   return BaseT::getAddressComputationCost(Ty, IsComplex);
890 }
891
892 unsigned X86TTIImpl::getReductionCost(unsigned Opcode, Type *ValTy,
893                                       bool IsPairwise) {
894
895   std::pair<unsigned, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
896
897   MVT MTy = LT.second;
898
899   int ISD = TLI->InstructionOpcodeToISD(Opcode);
900   assert(ISD && "Invalid opcode");
901
902   // We use the Intel Architecture Code Analyzer(IACA) to measure the throughput
903   // and make it as the cost.
904
905   static const CostTblEntry<MVT::SimpleValueType> SSE42CostTblPairWise[] = {
906     { ISD::FADD,  MVT::v2f64,   2 },
907     { ISD::FADD,  MVT::v4f32,   4 },
908     { ISD::ADD,   MVT::v2i64,   2 },      // The data reported by the IACA tool is "1.6".
909     { ISD::ADD,   MVT::v4i32,   3 },      // The data reported by the IACA tool is "3.5".
910     { ISD::ADD,   MVT::v8i16,   5 },
911   };
912
913   static const CostTblEntry<MVT::SimpleValueType> AVX1CostTblPairWise[] = {
914     { ISD::FADD,  MVT::v4f32,   4 },
915     { ISD::FADD,  MVT::v4f64,   5 },
916     { ISD::FADD,  MVT::v8f32,   7 },
917     { ISD::ADD,   MVT::v2i64,   1 },      // The data reported by the IACA tool is "1.5".
918     { ISD::ADD,   MVT::v4i32,   3 },      // The data reported by the IACA tool is "3.5".
919     { ISD::ADD,   MVT::v4i64,   5 },      // The data reported by the IACA tool is "4.8".
920     { ISD::ADD,   MVT::v8i16,   5 },
921     { ISD::ADD,   MVT::v8i32,   5 },
922   };
923
924   static const CostTblEntry<MVT::SimpleValueType> SSE42CostTblNoPairWise[] = {
925     { ISD::FADD,  MVT::v2f64,   2 },
926     { ISD::FADD,  MVT::v4f32,   4 },
927     { ISD::ADD,   MVT::v2i64,   2 },      // The data reported by the IACA tool is "1.6".
928     { ISD::ADD,   MVT::v4i32,   3 },      // The data reported by the IACA tool is "3.3".
929     { ISD::ADD,   MVT::v8i16,   4 },      // The data reported by the IACA tool is "4.3".
930   };
931
932   static const CostTblEntry<MVT::SimpleValueType> AVX1CostTblNoPairWise[] = {
933     { ISD::FADD,  MVT::v4f32,   3 },
934     { ISD::FADD,  MVT::v4f64,   3 },
935     { ISD::FADD,  MVT::v8f32,   4 },
936     { ISD::ADD,   MVT::v2i64,   1 },      // The data reported by the IACA tool is "1.5".
937     { ISD::ADD,   MVT::v4i32,   3 },      // The data reported by the IACA tool is "2.8".
938     { ISD::ADD,   MVT::v4i64,   3 },
939     { ISD::ADD,   MVT::v8i16,   4 },
940     { ISD::ADD,   MVT::v8i32,   5 },
941   };
942
943   if (IsPairwise) {
944     if (ST->hasAVX()) {
945       int Idx = CostTableLookup(AVX1CostTblPairWise, ISD, MTy);
946       if (Idx != -1)
947         return LT.first * AVX1CostTblPairWise[Idx].Cost;
948     }
949
950     if (ST->hasSSE42()) {
951       int Idx = CostTableLookup(SSE42CostTblPairWise, ISD, MTy);
952       if (Idx != -1)
953         return LT.first * SSE42CostTblPairWise[Idx].Cost;
954     }
955   } else {
956     if (ST->hasAVX()) {
957       int Idx = CostTableLookup(AVX1CostTblNoPairWise, ISD, MTy);
958       if (Idx != -1)
959         return LT.first * AVX1CostTblNoPairWise[Idx].Cost;
960     }
961
962     if (ST->hasSSE42()) {
963       int Idx = CostTableLookup(SSE42CostTblNoPairWise, ISD, MTy);
964       if (Idx != -1)
965         return LT.first * SSE42CostTblNoPairWise[Idx].Cost;
966     }
967   }
968
969   return BaseT::getReductionCost(Opcode, ValTy, IsPairwise);
970 }
971
972 /// \brief Calculate the cost of materializing a 64-bit value. This helper
973 /// method might only calculate a fraction of a larger immediate. Therefore it
974 /// is valid to return a cost of ZERO.
975 unsigned X86TTIImpl::getIntImmCost(int64_t Val) {
976   if (Val == 0)
977     return TTI::TCC_Free;
978
979   if (isInt<32>(Val))
980     return TTI::TCC_Basic;
981
982   return 2 * TTI::TCC_Basic;
983 }
984
985 unsigned X86TTIImpl::getIntImmCost(const APInt &Imm, Type *Ty) {
986   assert(Ty->isIntegerTy());
987
988   unsigned BitSize = Ty->getPrimitiveSizeInBits();
989   if (BitSize == 0)
990     return ~0U;
991
992   // Never hoist constants larger than 128bit, because this might lead to
993   // incorrect code generation or assertions in codegen.
994   // Fixme: Create a cost model for types larger than i128 once the codegen
995   // issues have been fixed.
996   if (BitSize > 128)
997     return TTI::TCC_Free;
998
999   if (Imm == 0)
1000     return TTI::TCC_Free;
1001
1002   // Sign-extend all constants to a multiple of 64-bit.
1003   APInt ImmVal = Imm;
1004   if (BitSize & 0x3f)
1005     ImmVal = Imm.sext((BitSize + 63) & ~0x3fU);
1006
1007   // Split the constant into 64-bit chunks and calculate the cost for each
1008   // chunk.
1009   unsigned Cost = 0;
1010   for (unsigned ShiftVal = 0; ShiftVal < BitSize; ShiftVal += 64) {
1011     APInt Tmp = ImmVal.ashr(ShiftVal).sextOrTrunc(64);
1012     int64_t Val = Tmp.getSExtValue();
1013     Cost += getIntImmCost(Val);
1014   }
1015   // We need at least one instruction to materialze the constant.
1016   return std::max(1U, Cost);
1017 }
1018
1019 unsigned X86TTIImpl::getIntImmCost(unsigned Opcode, unsigned Idx,
1020                                    const APInt &Imm, Type *Ty) {
1021   assert(Ty->isIntegerTy());
1022
1023   unsigned BitSize = Ty->getPrimitiveSizeInBits();
1024   // There is no cost model for constants with a bit size of 0. Return TCC_Free
1025   // here, so that constant hoisting will ignore this constant.
1026   if (BitSize == 0)
1027     return TTI::TCC_Free;
1028
1029   unsigned ImmIdx = ~0U;
1030   switch (Opcode) {
1031   default:
1032     return TTI::TCC_Free;
1033   case Instruction::GetElementPtr:
1034     // Always hoist the base address of a GetElementPtr. This prevents the
1035     // creation of new constants for every base constant that gets constant
1036     // folded with the offset.
1037     if (Idx == 0)
1038       return 2 * TTI::TCC_Basic;
1039     return TTI::TCC_Free;
1040   case Instruction::Store:
1041     ImmIdx = 0;
1042     break;
1043   case Instruction::Add:
1044   case Instruction::Sub:
1045   case Instruction::Mul:
1046   case Instruction::UDiv:
1047   case Instruction::SDiv:
1048   case Instruction::URem:
1049   case Instruction::SRem:
1050   case Instruction::And:
1051   case Instruction::Or:
1052   case Instruction::Xor:
1053   case Instruction::ICmp:
1054     ImmIdx = 1;
1055     break;
1056   // Always return TCC_Free for the shift value of a shift instruction.
1057   case Instruction::Shl:
1058   case Instruction::LShr:
1059   case Instruction::AShr:
1060     if (Idx == 1)
1061       return TTI::TCC_Free;
1062     break;
1063   case Instruction::Trunc:
1064   case Instruction::ZExt:
1065   case Instruction::SExt:
1066   case Instruction::IntToPtr:
1067   case Instruction::PtrToInt:
1068   case Instruction::BitCast:
1069   case Instruction::PHI:
1070   case Instruction::Call:
1071   case Instruction::Select:
1072   case Instruction::Ret:
1073   case Instruction::Load:
1074     break;
1075   }
1076
1077   if (Idx == ImmIdx) {
1078     unsigned NumConstants = (BitSize + 63) / 64;
1079     unsigned Cost = X86TTIImpl::getIntImmCost(Imm, Ty);
1080     return (Cost <= NumConstants * TTI::TCC_Basic)
1081                ? static_cast<unsigned>(TTI::TCC_Free)
1082                : Cost;
1083   }
1084
1085   return X86TTIImpl::getIntImmCost(Imm, Ty);
1086 }
1087
1088 unsigned X86TTIImpl::getIntImmCost(Intrinsic::ID IID, unsigned Idx,
1089                                    const APInt &Imm, Type *Ty) {
1090   assert(Ty->isIntegerTy());
1091
1092   unsigned BitSize = Ty->getPrimitiveSizeInBits();
1093   // There is no cost model for constants with a bit size of 0. Return TCC_Free
1094   // here, so that constant hoisting will ignore this constant.
1095   if (BitSize == 0)
1096     return TTI::TCC_Free;
1097
1098   switch (IID) {
1099   default:
1100     return TTI::TCC_Free;
1101   case Intrinsic::sadd_with_overflow:
1102   case Intrinsic::uadd_with_overflow:
1103   case Intrinsic::ssub_with_overflow:
1104   case Intrinsic::usub_with_overflow:
1105   case Intrinsic::smul_with_overflow:
1106   case Intrinsic::umul_with_overflow:
1107     if ((Idx == 1) && Imm.getBitWidth() <= 64 && isInt<32>(Imm.getSExtValue()))
1108       return TTI::TCC_Free;
1109     break;
1110   case Intrinsic::experimental_stackmap:
1111     if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
1112       return TTI::TCC_Free;
1113     break;
1114   case Intrinsic::experimental_patchpoint_void:
1115   case Intrinsic::experimental_patchpoint_i64:
1116     if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
1117       return TTI::TCC_Free;
1118     break;
1119   }
1120   return X86TTIImpl::getIntImmCost(Imm, Ty);
1121 }
1122
1123 bool X86TTIImpl::isLegalMaskedLoad(Type *DataTy, int Consecutive) {
1124   int DataWidth = DataTy->getPrimitiveSizeInBits();
1125
1126   // Todo: AVX512 allows gather/scatter, works with strided and random as well
1127   if ((DataWidth < 32) || (Consecutive == 0))
1128     return false;
1129   if (ST->hasAVX512() || ST->hasAVX2())
1130     return true;
1131   return false;
1132 }
1133
1134 bool X86TTIImpl::isLegalMaskedStore(Type *DataType, int Consecutive) {
1135   return isLegalMaskedLoad(DataType, Consecutive);
1136 }
1137
1138 bool X86TTIImpl::areInlineCompatible(const Function *Caller,
1139                                      const Function *Callee) const {
1140   const TargetMachine &TM = getTLI()->getTargetMachine();
1141
1142   // Work this as a subsetting of subtarget features.
1143   const FeatureBitset &CallerBits =
1144       TM.getSubtargetImpl(*Caller)->getFeatureBits();
1145   const FeatureBitset &CalleeBits =
1146       TM.getSubtargetImpl(*Callee)->getFeatureBits();
1147
1148   // FIXME: This is likely too limiting as it will include subtarget features
1149   // that we might not care about for inlining, but it is conservatively
1150   // correct.
1151   return (CallerBits & CalleeBits) == CalleeBits;
1152 }