Correctly testing for AVX support in x86 based off code from Hosts.cpp.
[oota-llvm.git] / lib / Target / X86 / X86Subtarget.cpp
1 //===-- X86Subtarget.cpp - X86 Subtarget Information ----------------------===//
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 //
10 // This file implements the X86 specific subclass of TargetSubtargetInfo.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "subtarget"
15 #include "X86Subtarget.h"
16 #include "X86InstrInfo.h"
17 #include "llvm/IR/Attributes.h"
18 #include "llvm/IR/Function.h"
19 #include "llvm/IR/GlobalValue.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/Host.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetOptions.h"
26
27 #define GET_SUBTARGETINFO_TARGET_DESC
28 #define GET_SUBTARGETINFO_CTOR
29 #include "X86GenSubtargetInfo.inc"
30
31 using namespace llvm;
32
33 #if defined(_MSC_VER)
34 #include <intrin.h>
35 #endif
36
37 /// ClassifyBlockAddressReference - Classify a blockaddress reference for the
38 /// current subtarget according to how we should reference it in a non-pcrel
39 /// context.
40 unsigned char X86Subtarget::ClassifyBlockAddressReference() const {
41   if (isPICStyleGOT())    // 32-bit ELF targets.
42     return X86II::MO_GOTOFF;
43
44   if (isPICStyleStubPIC())   // Darwin/32 in PIC mode.
45     return X86II::MO_PIC_BASE_OFFSET;
46
47   // Direct static reference to label.
48   return X86II::MO_NO_FLAG;
49 }
50
51 /// ClassifyGlobalReference - Classify a global variable reference for the
52 /// current subtarget according to how we should reference it in a non-pcrel
53 /// context.
54 unsigned char X86Subtarget::
55 ClassifyGlobalReference(const GlobalValue *GV, const TargetMachine &TM) const {
56   // DLLImport only exists on windows, it is implemented as a load from a
57   // DLLIMPORT stub.
58   if (GV->hasDLLImportLinkage())
59     return X86II::MO_DLLIMPORT;
60
61   // Determine whether this is a reference to a definition or a declaration.
62   // Materializable GVs (in JIT lazy compilation mode) do not require an extra
63   // load from stub.
64   bool isDecl = GV->hasAvailableExternallyLinkage();
65   if (GV->isDeclaration() && !GV->isMaterializable())
66     isDecl = true;
67
68   // X86-64 in PIC mode.
69   if (isPICStyleRIPRel()) {
70     // Large model never uses stubs.
71     if (TM.getCodeModel() == CodeModel::Large)
72       return X86II::MO_NO_FLAG;
73
74     if (isTargetDarwin()) {
75       // If symbol visibility is hidden, the extra load is not needed if
76       // target is x86-64 or the symbol is definitely defined in the current
77       // translation unit.
78       if (GV->hasDefaultVisibility() &&
79           (isDecl || GV->isWeakForLinker()))
80         return X86II::MO_GOTPCREL;
81     } else if (!isTargetWin64()) {
82       assert(isTargetELF() && "Unknown rip-relative target");
83
84       // Extra load is needed for all externally visible.
85       if (!GV->hasLocalLinkage() && GV->hasDefaultVisibility())
86         return X86II::MO_GOTPCREL;
87     }
88
89     return X86II::MO_NO_FLAG;
90   }
91
92   if (isPICStyleGOT()) {   // 32-bit ELF targets.
93     // Extra load is needed for all externally visible.
94     if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
95       return X86II::MO_GOTOFF;
96     return X86II::MO_GOT;
97   }
98
99   if (isPICStyleStubPIC()) {  // Darwin/32 in PIC mode.
100     // Determine whether we have a stub reference and/or whether the reference
101     // is relative to the PIC base or not.
102
103     // If this is a strong reference to a definition, it is definitely not
104     // through a stub.
105     if (!isDecl && !GV->isWeakForLinker())
106       return X86II::MO_PIC_BASE_OFFSET;
107
108     // Unless we have a symbol with hidden visibility, we have to go through a
109     // normal $non_lazy_ptr stub because this symbol might be resolved late.
110     if (!GV->hasHiddenVisibility())  // Non-hidden $non_lazy_ptr reference.
111       return X86II::MO_DARWIN_NONLAZY_PIC_BASE;
112
113     // If symbol visibility is hidden, we have a stub for common symbol
114     // references and external declarations.
115     if (isDecl || GV->hasCommonLinkage()) {
116       // Hidden $non_lazy_ptr reference.
117       return X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE;
118     }
119
120     // Otherwise, no stub.
121     return X86II::MO_PIC_BASE_OFFSET;
122   }
123
124   if (isPICStyleStubNoDynamic()) {  // Darwin/32 in -mdynamic-no-pic mode.
125     // Determine whether we have a stub reference.
126
127     // If this is a strong reference to a definition, it is definitely not
128     // through a stub.
129     if (!isDecl && !GV->isWeakForLinker())
130       return X86II::MO_NO_FLAG;
131
132     // Unless we have a symbol with hidden visibility, we have to go through a
133     // normal $non_lazy_ptr stub because this symbol might be resolved late.
134     if (!GV->hasHiddenVisibility())  // Non-hidden $non_lazy_ptr reference.
135       return X86II::MO_DARWIN_NONLAZY;
136
137     // Otherwise, no stub.
138     return X86II::MO_NO_FLAG;
139   }
140
141   // Direct static reference to global.
142   return X86II::MO_NO_FLAG;
143 }
144
145
146 /// getBZeroEntry - This function returns the name of a function which has an
147 /// interface like the non-standard bzero function, if such a function exists on
148 /// the current subtarget and it is considered prefereable over memset with zero
149 /// passed as the second argument. Otherwise it returns null.
150 const char *X86Subtarget::getBZeroEntry() const {
151   // Darwin 10 has a __bzero entry point for this purpose.
152   if (getTargetTriple().isMacOSX() &&
153       !getTargetTriple().isMacOSXVersionLT(10, 6))
154     return "__bzero";
155
156   return 0;
157 }
158
159 bool X86Subtarget::hasSinCos() const {
160   return getTargetTriple().isMacOSX() &&
161     !getTargetTriple().isMacOSXVersionLT(10, 9) &&
162     is64Bit();
163 }
164
165 /// IsLegalToCallImmediateAddr - Return true if the subtarget allows calls
166 /// to immediate address.
167 bool X86Subtarget::IsLegalToCallImmediateAddr(const TargetMachine &TM) const {
168   if (In64BitMode)
169     return false;
170   return isTargetELF() || TM.getRelocationModel() == Reloc::Static;
171 }
172
173 static bool OSHasAVXSupport() {
174 #if defined(__GNUC__)
175   // Check xgetbv; this uses a .byte sequence instead of the instruction
176   // directly because older assemblers do not include support for xgetbv and
177   // there is no easy way to conditionally compile based on the assembler used.
178   int rEAX, rEDX;
179   __asm__ (".byte 0x0f, 0x01, 0xd0" : "=a" (rEAX), "=d" (rEDX) : "c" (0));
180 #elif defined(_MSC_FULL_VER) && defined(_XCR_XFEATURE_ENABLED_MASK)
181   unsigned long long rEAX = _xgetbv(_XCR_XFEATURE_ENABLED_MASK);
182 #else
183   int rEAX = 0; // Ensures we return false
184 #endif
185   return (rEAX & 6) == 6;
186 }
187
188 void X86Subtarget::AutoDetectSubtargetFeatures() {
189   unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0;
190   unsigned MaxLevel;
191   union {
192     unsigned u[3];
193     char     c[12];
194   } text;
195
196   if (X86_MC::GetCpuIDAndInfo(0, &MaxLevel, text.u+0, text.u+2, text.u+1) ||
197       MaxLevel < 1)
198     return;
199
200   X86_MC::GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX);
201
202   if ((EDX >> 15) & 1) { HasCMov = true;      ToggleFeature(X86::FeatureCMOV); }
203   if ((EDX >> 23) & 1) { X86SSELevel = MMX;   ToggleFeature(X86::FeatureMMX);  }
204   if ((EDX >> 25) & 1) { X86SSELevel = SSE1;  ToggleFeature(X86::FeatureSSE1); }
205   if ((EDX >> 26) & 1) { X86SSELevel = SSE2;  ToggleFeature(X86::FeatureSSE2); }
206   if (ECX & 0x1)       { X86SSELevel = SSE3;  ToggleFeature(X86::FeatureSSE3); }
207   if ((ECX >> 9)  & 1) { X86SSELevel = SSSE3; ToggleFeature(X86::FeatureSSSE3);}
208   if ((ECX >> 19) & 1) { X86SSELevel = SSE41; ToggleFeature(X86::FeatureSSE41);}
209   if ((ECX >> 20) & 1) { X86SSELevel = SSE42; ToggleFeature(X86::FeatureSSE42);}
210   if (((ECX >> 27) & 1) && ((ECX >> 28) & 1) && OSHasAVXSupport()) {
211     X86SSELevel = AVX;   ToggleFeature(X86::FeatureAVX);
212   }
213
214   bool IsIntel = memcmp(text.c, "GenuineIntel", 12) == 0;
215   bool IsAMD   = !IsIntel && memcmp(text.c, "AuthenticAMD", 12) == 0;
216
217   if ((ECX >> 1) & 0x1) {
218     HasPCLMUL = true;
219     ToggleFeature(X86::FeaturePCLMUL);
220   }
221   if ((ECX >> 12) & 0x1) {
222     HasFMA = true;
223     ToggleFeature(X86::FeatureFMA);
224   }
225   if (IsIntel && ((ECX >> 22) & 0x1)) {
226     HasMOVBE = true;
227     ToggleFeature(X86::FeatureMOVBE);
228   }
229   if ((ECX >> 23) & 0x1) {
230     HasPOPCNT = true;
231     ToggleFeature(X86::FeaturePOPCNT);
232   }
233   if ((ECX >> 25) & 0x1) {
234     HasAES = true;
235     ToggleFeature(X86::FeatureAES);
236   }
237   if ((ECX >> 29) & 0x1) {
238     HasF16C = true;
239     ToggleFeature(X86::FeatureF16C);
240   }
241   if (IsIntel && ((ECX >> 30) & 0x1)) {
242     HasRDRAND = true;
243     ToggleFeature(X86::FeatureRDRAND);
244   }
245
246   if ((ECX >> 13) & 0x1) {
247     HasCmpxchg16b = true;
248     ToggleFeature(X86::FeatureCMPXCHG16B);
249   }
250
251   if (IsIntel || IsAMD) {
252     // Determine if bit test memory instructions are slow.
253     unsigned Family = 0;
254     unsigned Model  = 0;
255     X86_MC::DetectFamilyModel(EAX, Family, Model);
256     if (IsAMD || (Family == 6 && Model >= 13)) {
257       IsBTMemSlow = true;
258       ToggleFeature(X86::FeatureSlowBTMem);
259     }
260
261     // If it's an Intel chip since Nehalem and not an Atom chip, unaligned
262     // memory access is fast. We hard code model numbers here because they
263     // aren't strictly increasing for Intel chips it seems.
264     if (IsIntel &&
265         ((Family == 6 && Model == 0x1E) || // Nehalem: Clarksfield, Lynnfield,
266                                            //          Jasper Froest
267          (Family == 6 && Model == 0x1A) || // Nehalem: Bloomfield, Nehalem-EP
268          (Family == 6 && Model == 0x2E) || // Nehalem: Nehalem-EX
269          (Family == 6 && Model == 0x25) || // Westmere: Arrandale, Clarksdale
270          (Family == 6 && Model == 0x2C) || // Westmere: Gulftown, Westmere-EP
271          (Family == 6 && Model == 0x2F) || // Westmere: Westmere-EX
272          (Family == 6 && Model == 0x2A) || // SandyBridge
273          (Family == 6 && Model == 0x2D) || // SandyBridge: SandyBridge-E*
274          (Family == 6 && Model == 0x3A))) {// IvyBridge
275       IsUAMemFast = true;
276       ToggleFeature(X86::FeatureFastUAMem);
277     }
278
279     // Set processor type. Currently only Atom is detected.
280     if (Family == 6 &&
281         (Model == 28 || Model == 38 || Model == 39
282          || Model == 53 || Model == 54)) {
283       X86ProcFamily = IntelAtom;
284
285       UseLeaForSP = true;
286       ToggleFeature(X86::FeatureLeaForSP);
287     }
288
289     unsigned MaxExtLevel;
290     X86_MC::GetCpuIDAndInfo(0x80000000, &MaxExtLevel, &EBX, &ECX, &EDX);
291
292     if (MaxExtLevel >= 0x80000001) {
293       X86_MC::GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX);
294       if ((EDX >> 29) & 0x1) {
295         HasX86_64 = true;
296         ToggleFeature(X86::Feature64Bit);
297       }
298       if ((ECX >> 5) & 0x1) {
299         HasLZCNT = true;
300         ToggleFeature(X86::FeatureLZCNT);
301       }
302       if (IsIntel && ((ECX >> 8) & 0x1)) {
303         HasPRFCHW = true;
304         ToggleFeature(X86::FeaturePRFCHW);
305       }
306       if (IsAMD) {
307         if ((ECX >> 6) & 0x1) {
308           HasSSE4A = true;
309           ToggleFeature(X86::FeatureSSE4A);
310         }
311         if ((ECX >> 11) & 0x1) {
312           HasXOP = true;
313           ToggleFeature(X86::FeatureXOP);
314         }
315         if ((ECX >> 16) & 0x1) {
316           HasFMA4 = true;
317           ToggleFeature(X86::FeatureFMA4);
318         }
319       }
320     }
321   }
322
323   if (MaxLevel >= 7) {
324     if (!X86_MC::GetCpuIDAndInfoEx(0x7, 0x0, &EAX, &EBX, &ECX, &EDX)) {
325       if (IsIntel && (EBX & 0x1)) {
326         HasFSGSBase = true;
327         ToggleFeature(X86::FeatureFSGSBase);
328       }
329       if ((EBX >> 3) & 0x1) {
330         HasBMI = true;
331         ToggleFeature(X86::FeatureBMI);
332       }
333       if ((EBX >> 4) & 0x1) {
334         HasHLE = true;
335         ToggleFeature(X86::FeatureHLE);
336       }
337       if (IsIntel && ((EBX >> 5) & 0x1)) {
338         X86SSELevel = AVX2;
339         ToggleFeature(X86::FeatureAVX2);
340       }
341       if (IsIntel && ((EBX >> 8) & 0x1)) {
342         HasBMI2 = true;
343         ToggleFeature(X86::FeatureBMI2);
344       }
345       if (IsIntel && ((EBX >> 11) & 0x1)) {
346         HasRTM = true;
347         ToggleFeature(X86::FeatureRTM);
348       }
349       if (IsIntel && ((EBX >> 19) & 0x1)) {
350         HasADX = true;
351         ToggleFeature(X86::FeatureADX);
352       }
353       if (IsIntel && ((EBX >> 18) & 0x1)) {
354         HasRDSEED = true;
355         ToggleFeature(X86::FeatureRDSEED);
356       }
357     }
358   }
359 }
360
361 void X86Subtarget::resetSubtargetFeatures(const MachineFunction *MF) {
362   AttributeSet FnAttrs = MF->getFunction()->getAttributes();
363   Attribute CPUAttr = FnAttrs.getAttribute(AttributeSet::FunctionIndex,
364                                            "target-cpu");
365   Attribute FSAttr = FnAttrs.getAttribute(AttributeSet::FunctionIndex,
366                                           "target-features");
367   std::string CPU =
368     !CPUAttr.hasAttribute(Attribute::None) ?CPUAttr.getValueAsString() : "";
369   std::string FS =
370     !FSAttr.hasAttribute(Attribute::None) ? FSAttr.getValueAsString() : "";
371   if (!FS.empty()) {
372     initializeEnvironment();
373     resetSubtargetFeatures(CPU, FS);
374   }
375 }
376
377 void X86Subtarget::resetSubtargetFeatures(StringRef CPU, StringRef FS) {
378   std::string CPUName = CPU;
379   if (!FS.empty() || !CPU.empty()) {
380     if (CPUName.empty()) {
381 #if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86)\
382     || defined(__x86_64__) || defined(_M_AMD64) || defined (_M_X64)
383       CPUName = sys::getHostCPUName();
384 #else
385       CPUName = "generic";
386 #endif
387     }
388
389     // Make sure 64-bit features are available in 64-bit mode. (But make sure
390     // SSE2 can be turned off explicitly.)
391     std::string FullFS = FS;
392     if (In64BitMode) {
393       if (!FullFS.empty())
394         FullFS = "+64bit,+sse2," + FullFS;
395       else
396         FullFS = "+64bit,+sse2";
397     }
398
399     // If feature string is not empty, parse features string.
400     ParseSubtargetFeatures(CPUName, FullFS);
401   } else {
402     if (CPUName.empty()) {
403 #if defined (__x86_64__) || defined(__i386__)
404       CPUName = sys::getHostCPUName();
405 #else
406       CPUName = "generic";
407 #endif
408     }
409     // Otherwise, use CPUID to auto-detect feature set.
410     AutoDetectSubtargetFeatures();
411
412     // Make sure 64-bit features are available in 64-bit mode.
413     if (In64BitMode) {
414       HasX86_64 = true; ToggleFeature(X86::Feature64Bit);
415       HasCMov = true;   ToggleFeature(X86::FeatureCMOV);
416
417       if (X86SSELevel < SSE2) {
418         X86SSELevel = SSE2;
419         ToggleFeature(X86::FeatureSSE1);
420         ToggleFeature(X86::FeatureSSE2);
421       }
422     }
423   }
424
425   // CPUName may have been set by the CPU detection code. Make sure the
426   // new MCSchedModel is used.
427   InitMCProcessorInfo(CPUName, FS);
428
429   if (X86ProcFamily == IntelAtom)
430     PostRAScheduler = true;
431
432   InstrItins = getInstrItineraryForCPU(CPUName);
433
434   // It's important to keep the MCSubtargetInfo feature bits in sync with
435   // target data structure which is shared with MC code emitter, etc.
436   if (In64BitMode)
437     ToggleFeature(X86::Mode64Bit);
438
439   DEBUG(dbgs() << "Subtarget features: SSELevel " << X86SSELevel
440                << ", 3DNowLevel " << X863DNowLevel
441                << ", 64bit " << HasX86_64 << "\n");
442   assert((!In64BitMode || HasX86_64) &&
443          "64-bit code requested on a subtarget that doesn't support it!");
444
445   // Stack alignment is 16 bytes on Darwin, Linux and Solaris (both
446   // 32 and 64 bit) and for all 64-bit targets.
447   if (StackAlignOverride)
448     stackAlignment = StackAlignOverride;
449   else if (isTargetDarwin() || isTargetLinux() || isTargetSolaris() ||
450            In64BitMode)
451     stackAlignment = 16;
452 }
453
454 void X86Subtarget::initializeEnvironment() {
455   X86SSELevel = NoMMXSSE;
456   X863DNowLevel = NoThreeDNow;
457   HasCMov = false;
458   HasX86_64 = false;
459   HasPOPCNT = false;
460   HasSSE4A = false;
461   HasAES = false;
462   HasPCLMUL = false;
463   HasFMA = false;
464   HasFMA4 = false;
465   HasXOP = false;
466   HasMOVBE = false;
467   HasRDRAND = false;
468   HasF16C = false;
469   HasFSGSBase = false;
470   HasLZCNT = false;
471   HasBMI = false;
472   HasBMI2 = false;
473   HasRTM = false;
474   HasHLE = false;
475   HasADX = false;
476   HasPRFCHW = false;
477   HasRDSEED = false;
478   IsBTMemSlow = false;
479   IsUAMemFast = false;
480   HasVectorUAMem = false;
481   HasCmpxchg16b = false;
482   UseLeaForSP = false;
483   HasSlowDivide = false;
484   PostRAScheduler = false;
485   PadShortFunctions = false;
486   CallRegIndirect = false;
487   LEAUsesAG = false;
488   stackAlignment = 4;
489   // FIXME: this is a known good value for Yonah. How about others?
490   MaxInlineSizeThreshold = 128;
491 }
492
493 X86Subtarget::X86Subtarget(const std::string &TT, const std::string &CPU,
494                            const std::string &FS,
495                            unsigned StackAlignOverride, bool is64Bit)
496   : X86GenSubtargetInfo(TT, CPU, FS)
497   , X86ProcFamily(Others)
498   , PICStyle(PICStyles::None)
499   , TargetTriple(TT)
500   , StackAlignOverride(StackAlignOverride)
501   , In64BitMode(is64Bit) {
502   initializeEnvironment();
503   resetSubtargetFeatures(CPU, FS);
504 }
505
506 bool X86Subtarget::enablePostRAScheduler(
507            CodeGenOpt::Level OptLevel,
508            TargetSubtargetInfo::AntiDepBreakMode& Mode,
509            RegClassVector& CriticalPathRCs) const {
510   Mode = TargetSubtargetInfo::ANTIDEP_CRITICAL;
511   CriticalPathRCs.clear();
512   return PostRAScheduler && OptLevel >= CodeGenOpt::Default;
513 }