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 #include "X86.h"
15 
16 #include "X86CallLowering.h"
17 #include "X86LegalizerInfo.h"
18 #include "X86RegisterBankInfo.h"
19 #include "X86Subtarget.h"
20 #include "MCTargetDesc/X86BaseInfo.h"
21 #include "X86TargetMachine.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/GlobalISel/CallLowering.h"
24 #include "llvm/CodeGen/GlobalISel/InstructionSelect.h"
25 #include "llvm/CodeGen/GlobalISel/Legalizer.h"
26 #include "llvm/CodeGen/GlobalISel/RegBankSelect.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/ConstantRange.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/GlobalValue.h"
31 #include "llvm/Support/Casting.h"
32 #include "llvm/Support/CodeGen.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include <cassert>
39 #include <string>
40 
41 #if defined(_MSC_VER)
42 #include <intrin.h>
43 #endif
44 
45 using namespace llvm;
46 
47 #define DEBUG_TYPE "subtarget"
48 
49 #define GET_SUBTARGETINFO_TARGET_DESC
50 #define GET_SUBTARGETINFO_CTOR
51 #include "X86GenSubtargetInfo.inc"
52 
53 // Temporary option to control early if-conversion for x86 while adding machine
54 // models.
55 static cl::opt<bool>
56 X86EarlyIfConv("x86-early-ifcvt", cl::Hidden,
57                cl::desc("Enable early if-conversion on X86"));
58 
59 
60 /// Classify a blockaddress reference for the current subtarget according to how
61 /// we should reference it in a non-pcrel context.
62 unsigned char X86Subtarget::classifyBlockAddressReference() const {
63   return classifyLocalReference(nullptr);
64 }
65 
66 /// Classify a global variable reference for the current subtarget according to
67 /// how we should reference it in a non-pcrel context.
68 unsigned char
69 X86Subtarget::classifyGlobalReference(const GlobalValue *GV) const {
70   return classifyGlobalReference(GV, *GV->getParent());
71 }
72 
73 unsigned char
74 X86Subtarget::classifyLocalReference(const GlobalValue *GV) const {
75   // 64 bits can use %rip addressing for anything local.
76   if (is64Bit())
77     return X86II::MO_NO_FLAG;
78 
79   // If this is for a position dependent executable, the static linker can
80   // figure it out.
81   if (!isPositionIndependent())
82     return X86II::MO_NO_FLAG;
83 
84   // The COFF dynamic linker just patches the executable sections.
85   if (isTargetCOFF())
86     return X86II::MO_NO_FLAG;
87 
88   if (isTargetDarwin()) {
89     // 32 bit macho has no relocation for a-b if a is undefined, even if
90     // b is in the section that is being relocated.
91     // This means we have to use o load even for GVs that are known to be
92     // local to the dso.
93     if (GV && (GV->isDeclarationForLinker() || GV->hasCommonLinkage()))
94       return X86II::MO_DARWIN_NONLAZY_PIC_BASE;
95 
96     return X86II::MO_PIC_BASE_OFFSET;
97   }
98 
99   return X86II::MO_GOTOFF;
100 }
101 
102 unsigned char X86Subtarget::classifyGlobalReference(const GlobalValue *GV,
103                                                     const Module &M) const {
104   // Large model never uses stubs.
105   if (TM.getCodeModel() == CodeModel::Large)
106     return X86II::MO_NO_FLAG;
107 
108   // Absolute symbols can be referenced directly.
109   if (GV) {
110     if (Optional<ConstantRange> CR = GV->getAbsoluteSymbolRange()) {
111       // See if we can use the 8-bit immediate form. Note that some instructions
112       // will sign extend the immediate operand, so to be conservative we only
113       // accept the range [0,128).
114       if (CR->getUnsignedMax().ult(128))
115         return X86II::MO_ABS8;
116       else
117         return X86II::MO_NO_FLAG;
118     }
119   }
120 
121   if (TM.shouldAssumeDSOLocal(M, GV))
122     return classifyLocalReference(GV);
123 
124   if (isTargetCOFF())
125     return X86II::MO_DLLIMPORT;
126 
127   if (is64Bit())
128     return X86II::MO_GOTPCREL;
129 
130   if (isTargetDarwin()) {
131     if (!isPositionIndependent())
132       return X86II::MO_DARWIN_NONLAZY;
133     return X86II::MO_DARWIN_NONLAZY_PIC_BASE;
134   }
135 
136   return X86II::MO_GOT;
137 }
138 
139 unsigned char
140 X86Subtarget::classifyGlobalFunctionReference(const GlobalValue *GV) const {
141   return classifyGlobalFunctionReference(GV, *GV->getParent());
142 }
143 
144 unsigned char
145 X86Subtarget::classifyGlobalFunctionReference(const GlobalValue *GV,
146                                               const Module &M) const {
147   if (TM.shouldAssumeDSOLocal(M, GV))
148     return X86II::MO_NO_FLAG;
149 
150   if (isTargetCOFF()) {
151     assert(GV->hasDLLImportStorageClass() &&
152            "shouldAssumeDSOLocal gave inconsistent answer");
153     return X86II::MO_DLLIMPORT;
154   }
155 
156   const Function *F = dyn_cast_or_null<Function>(GV);
157 
158   if (isTargetELF()) {
159     if (is64Bit() && F && (CallingConv::X86_RegCall == F->getCallingConv()))
160       // According to psABI, PLT stub clobbers XMM8-XMM15.
161       // In Regcall calling convention those registers are used for passing
162       // parameters. Thus we need to prevent lazy binding in Regcall.
163       return X86II::MO_GOTPCREL;
164     if (F && F->hasFnAttribute(Attribute::NonLazyBind) && is64Bit())
165       return X86II::MO_GOTPCREL;
166     return X86II::MO_PLT;
167   }
168 
169   if (is64Bit()) {
170     if (F && F->hasFnAttribute(Attribute::NonLazyBind))
171       // If the function is marked as non-lazy, generate an indirect call
172       // which loads from the GOT directly. This avoids runtime overhead
173       // at the cost of eager binding (and one extra byte of encoding).
174       return X86II::MO_GOTPCREL;
175     return X86II::MO_NO_FLAG;
176   }
177 
178   return X86II::MO_NO_FLAG;
179 }
180 
181 /// This function returns the name of a function which has an interface like
182 /// the non-standard bzero function, if such a function exists on the
183 /// current subtarget and it is considered preferable over memset with zero
184 /// passed as the second argument. Otherwise it returns null.
185 const char *X86Subtarget::getBZeroEntry() const {
186   // Darwin 10 has a __bzero entry point for this purpose.
187   if (getTargetTriple().isMacOSX() &&
188       !getTargetTriple().isMacOSXVersionLT(10, 6))
189     return "__bzero";
190 
191   return nullptr;
192 }
193 
194 bool X86Subtarget::hasSinCos() const {
195   if (getTargetTriple().isMacOSX()) {
196     return !getTargetTriple().isMacOSXVersionLT(10, 9) && is64Bit();
197   } else if (getTargetTriple().isOSFuchsia()) {
198     return true;
199   }
200   return false;
201 }
202 
203 /// Return true if the subtarget allows calls to immediate address.
204 bool X86Subtarget::isLegalToCallImmediateAddr() const {
205   // FIXME: I386 PE/COFF supports PC relative calls using IMAGE_REL_I386_REL32
206   // but WinCOFFObjectWriter::RecordRelocation cannot emit them.  Once it does,
207   // the following check for Win32 should be removed.
208   if (In64BitMode || isTargetWin32())
209     return false;
210   return isTargetELF() || TM.getRelocationModel() == Reloc::Static;
211 }
212 
213 void X86Subtarget::initSubtargetFeatures(StringRef CPU, StringRef FS) {
214   std::string CPUName = CPU;
215   if (CPUName.empty())
216     CPUName = "generic";
217 
218   // Make sure 64-bit features are available in 64-bit mode. (But make sure
219   // SSE2 can be turned off explicitly.)
220   std::string FullFS = FS;
221   if (In64BitMode) {
222     if (!FullFS.empty())
223       FullFS = "+64bit,+sse2," + FullFS;
224     else
225       FullFS = "+64bit,+sse2";
226   }
227 
228   // LAHF/SAHF are always supported in non-64-bit mode.
229   if (!In64BitMode) {
230     if (!FullFS.empty())
231       FullFS = "+sahf," + FullFS;
232     else
233       FullFS = "+sahf";
234   }
235 
236   // Parse features string and set the CPU.
237   ParseSubtargetFeatures(CPUName, FullFS);
238 
239   // All CPUs that implement SSE4.2 or SSE4A support unaligned accesses of
240   // 16-bytes and under that are reasonably fast. These features were
241   // introduced with Intel's Nehalem/Silvermont and AMD's Family10h
242   // micro-architectures respectively.
243   if (hasSSE42() || hasSSE4A())
244     IsUAMem16Slow = false;
245 
246   InstrItins = getInstrItineraryForCPU(CPUName);
247 
248   // It's important to keep the MCSubtargetInfo feature bits in sync with
249   // target data structure which is shared with MC code emitter, etc.
250   if (In64BitMode)
251     ToggleFeature(X86::Mode64Bit);
252   else if (In32BitMode)
253     ToggleFeature(X86::Mode32Bit);
254   else if (In16BitMode)
255     ToggleFeature(X86::Mode16Bit);
256   else
257     llvm_unreachable("Not 16-bit, 32-bit or 64-bit mode!");
258 
259   DEBUG(dbgs() << "Subtarget features: SSELevel " << X86SSELevel
260                << ", 3DNowLevel " << X863DNowLevel
261                << ", 64bit " << HasX86_64 << "\n");
262   assert((!In64BitMode || HasX86_64) &&
263          "64-bit code requested on a subtarget that doesn't support it!");
264 
265   // Stack alignment is 16 bytes on Darwin, Linux, kFreeBSD and Solaris (both
266   // 32 and 64 bit) and for all 64-bit targets.
267   if (StackAlignOverride)
268     stackAlignment = StackAlignOverride;
269   else if (isTargetDarwin() || isTargetLinux() || isTargetSolaris() ||
270            isTargetKFreeBSD() || In64BitMode)
271     stackAlignment = 16;
272 
273   // Some CPUs have more overhead for gather. The specified overhead is relative
274   // to the Load operation. "2" is the number provided by Intel architects. This
275   // parameter is used for cost estimation of Gather Op and comparison with
276   // other alternatives.
277   // TODO: Remove the explicit hasAVX512()?, That would mean we would only
278   // enable gather with a -march.
279   if (hasAVX512() || (hasAVX2() && hasFastGather()))
280     GatherOverhead = 2;
281   if (hasAVX512())
282     ScatterOverhead = 2;
283 }
284 
285 void X86Subtarget::initializeEnvironment() {
286   X86SSELevel = NoSSE;
287   X863DNowLevel = NoThreeDNow;
288   HasX87 = false;
289   HasCMov = false;
290   HasX86_64 = false;
291   HasPOPCNT = false;
292   HasSSE4A = false;
293   HasAES = false;
294   HasVAES = false;
295   HasFXSR = false;
296   HasXSAVE = false;
297   HasXSAVEOPT = false;
298   HasXSAVEC = false;
299   HasXSAVES = false;
300   HasPCLMUL = false;
301   HasVPCLMULQDQ = false;
302   HasGFNI = false;
303   HasFMA = false;
304   HasFMA4 = false;
305   HasXOP = false;
306   HasTBM = false;
307   HasLWP = false;
308   HasMOVBE = false;
309   HasRDRAND = false;
310   HasF16C = false;
311   HasFSGSBase = false;
312   HasLZCNT = false;
313   HasBMI = false;
314   HasBMI2 = false;
315   HasVBMI = false;
316   HasVBMI2 = false;
317   HasIFMA = false;
318   HasRTM = false;
319   HasERI = false;
320   HasCDI = false;
321   HasPFI = false;
322   HasDQI = false;
323   HasVPOPCNTDQ = false;
324   HasBWI = false;
325   HasVLX = false;
326   HasADX = false;
327   HasPKU = false;
328   HasVNNI = false;
329   HasBITALG = false;
330   HasSHA = false;
331   HasPRFCHW = false;
332   HasRDSEED = false;
333   HasLAHFSAHF = false;
334   HasMWAITX = false;
335   HasCLZERO = false;
336   HasMPX = false;
337   HasSHSTK = false;
338   HasIBT = false;
339   HasSGX = false;
340   HasCLFLUSHOPT = false;
341   HasCLWB = false;
342   IsPMULLDSlow = false;
343   IsSHLDSlow = false;
344   IsUAMem16Slow = false;
345   IsUAMem32Slow = false;
346   HasSSEUnalignedMem = false;
347   HasCmpxchg16b = false;
348   UseLeaForSP = false;
349   HasFastPartialYMMorZMMWrite = false;
350   HasFastGather = false;
351   HasFastScalarFSQRT = false;
352   HasFastVectorFSQRT = false;
353   HasFastLZCNT = false;
354   HasFastSHLDRotate = false;
355   HasMacroFusion = false;
356   HasERMSB = false;
357   HasSlowDivide32 = false;
358   HasSlowDivide64 = false;
359   PadShortFunctions = false;
360   SlowTwoMemOps = false;
361   LEAUsesAG = false;
362   SlowLEA = false;
363   Slow3OpsLEA = false;
364   SlowIncDec = false;
365   stackAlignment = 4;
366   // FIXME: this is a known good value for Yonah. How about others?
367   MaxInlineSizeThreshold = 128;
368   UseSoftFloat = false;
369   X86ProcFamily = Others;
370   GatherOverhead = 1024;
371   ScatterOverhead = 1024;
372 }
373 
374 X86Subtarget &X86Subtarget::initializeSubtargetDependencies(StringRef CPU,
375                                                             StringRef FS) {
376   initializeEnvironment();
377   initSubtargetFeatures(CPU, FS);
378   return *this;
379 }
380 
381 X86Subtarget::X86Subtarget(const Triple &TT, StringRef CPU, StringRef FS,
382                            const X86TargetMachine &TM,
383                            unsigned StackAlignOverride)
384     : X86GenSubtargetInfo(TT, CPU, FS), X86ProcFamily(Others),
385       PICStyle(PICStyles::None), TM(TM), TargetTriple(TT),
386       StackAlignOverride(StackAlignOverride),
387       In64BitMode(TargetTriple.getArch() == Triple::x86_64),
388       In32BitMode(TargetTriple.getArch() == Triple::x86 &&
389                   TargetTriple.getEnvironment() != Triple::CODE16),
390       In16BitMode(TargetTriple.getArch() == Triple::x86 &&
391                   TargetTriple.getEnvironment() == Triple::CODE16),
392       InstrInfo(initializeSubtargetDependencies(CPU, FS)), TLInfo(TM, *this),
393       FrameLowering(*this, getStackAlignment()) {
394   // Determine the PICStyle based on the target selected.
395   if (!isPositionIndependent())
396     setPICStyle(PICStyles::None);
397   else if (is64Bit())
398     setPICStyle(PICStyles::RIPRel);
399   else if (isTargetCOFF())
400     setPICStyle(PICStyles::None);
401   else if (isTargetDarwin())
402     setPICStyle(PICStyles::StubPIC);
403   else if (isTargetELF())
404     setPICStyle(PICStyles::GOT);
405 
406   CallLoweringInfo.reset(new X86CallLowering(*getTargetLowering()));
407   Legalizer.reset(new X86LegalizerInfo(*this, TM));
408 
409   auto *RBI = new X86RegisterBankInfo(*getRegisterInfo());
410   RegBankInfo.reset(RBI);
411   InstSelector.reset(createX86InstructionSelector(TM, *this, *RBI));
412 }
413 
414 const CallLowering *X86Subtarget::getCallLowering() const {
415   return CallLoweringInfo.get();
416 }
417 
418 const InstructionSelector *X86Subtarget::getInstructionSelector() const {
419   return InstSelector.get();
420 }
421 
422 const LegalizerInfo *X86Subtarget::getLegalizerInfo() const {
423   return Legalizer.get();
424 }
425 
426 const RegisterBankInfo *X86Subtarget::getRegBankInfo() const {
427   return RegBankInfo.get();
428 }
429 
430 bool X86Subtarget::enableEarlyIfConversion() const {
431   return hasCMov() && X86EarlyIfConv;
432 }
433