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